JTypeTimeout function starts execution too many times

I created a loop with the setTimeout function, and it comes to the problem after the second or third step, which it calls itself, because it starts to exit twice at that time. This is what my function looks like:

var value = 70, intervalID = null; function interval() { intervalID = setTimeout(countDown, 1000); } function countDown() { value--; if(value > 0) { clearTimeout(intervalID); interval(); } else { endInterval(); } } function endInterval() { // do something } 

If I console the value of the variable to 69, 68, and after that it starts to decrease the value of the variable twice in one function call. I do not call the countDown () function anywhere, but from one place.

Javascript Interval What could be the problem?

Edit: this code is working now.

+4
source share
1 answer

I would recommend that you โ€œsanitizeโ€ timeouts by stopping the previous one.

 function interval() { clearTimeout(intervalID); intervalID = setTimeout(countDown, 1000); } 

However, this is similar to symptom control, not a disease. Therefore, it would be better to determine the cause of the problem.

+4
source

All Articles