Answer the question
In order to leave comments, you need to log in
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
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 theif (n >= num) {
clearInterval(interval);
l.innerHTML = num;
return;
}
l.innerHTML = n;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question