Kevin Powell - CommunityKP-C
Kevin Powell - Communityβ€’3y agoβ€’
3 replies
;_;

Why function does work different?

Hi, I coded a function that counts from 0 to the value provided by HTML. I also have function that starts the counter when the user scrolls to the section ".advantages". When I call the function "counter()" independently it works fine, but when I call it inside another function, the counting process becomes much faster and I can't prevent that. Can someone explain why does that happen? The commented "counter()" works fine, the "counter()" in the event listener doesn't work how I want it to.

  const number = document.querySelectorAll(".number");
  const advantages = document.querySelector('.advantages');
  const speed = 100;
  function counter() {
    number.forEach(element => {
      incNumber(element);
    });
    function incNumber(elem) {
      let text = +elem.innerText;
      const value = +elem.getAttribute("data-count");
      const inc = Math.ceil(value / speed);
      if(text < value) {
        elem.innerText = inc + text;
        setTimeout(() => {
          incNumber(elem);
        }, 20);
      } else {
        elem.style.marginLeft = "0.5em";
        elem.innerText = value;
      }
    }
}

// counter();


  function isInViewport(el) {
    const rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)

    );
}


document.addEventListener('scroll', function () {
    if(isInViewport(advantages)) {
      counter();
    }

}, {
    passive: true
});
Was this page helpful?