New to JS, trying to stop my div from counting once the counting has completed

Basically i’m a beginner at JS, I’m trying to make this div start counting up when the div scrolls into view and stop counting once its finished counting. I managed to get it kind of working briefly but everytime I scrolled it would start counting again.

Any help is greatly appreciated, thanks.

let stats = document.getElementById('.container-stats');

stats.addEventListener("scroll", () => {
 function counter(id, start, end, duration) {
  let obj = document.getElementById(id),
   current = start,
   range = end - start,
   increment = end > start ? 1 : -1,
   step = Math.abs(Math.floor(duration / range)),
   timer = setInterval(() => {
    current += increment;
    obj.textContent = current;
    if (current == end) {
     clearInterval(timer);
    }
   }, step);
 }
 counter("count1", 0, 6, 3000);
 counter("count2", 100, 40, 3000);
 counter("count3", 499000, 500000, 3000);
 counter("count4", 0, 10, 3000);
 counter("count5", 0, 12, 3000);
 counter("count6", 0, 10, 3000);
});

1 thought on “New to JS, trying to stop my div from counting once the counting has completed”

Leave a Comment