M
M
MRcracker2022-04-20 14:04:07
JavaScript
MRcracker, 2022-04-20 14:04:07

How to set the counter correctly?

There is a small function that should increase the number and when the number is 1557, the increase should stop.

Tell me where I made a mistake, because I have an infinite increase.

document.addEventListener("DOMContentLoaded", () => {
  const time = 4000;
  const step = 100;

const outNum = (num, elem) => {
    let l = document.querySelector('#' + elem);
    n = 0;
    let time = Math.round(time/(num/step));
    let interval = setInterval(() =>{
      n = n + step;
      if (n == num) {
        clearInterval(interval);
      }
      l.innerHTML = n;
    }, time)
  }
  outNum(1557, 'out-1');
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
goshaLoonny, 2022-04-20
@MRcracker

You have a step of 100. 1557 is not divisible by 100, which means that the condition will never be met, which is why an infinite increase occurs. In addition, as far as I can see this is an infinite recursion, there are no conditions for exiting the recursion. Change

if (n == num) {
  clearInterval(interval);
}
l.innerHTML = n;
on the
if (n >= num) {
  clearInterval(interval);
  l.innerHTML = num;
  return;
}
l.innerHTML = n;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question