Reputation: 199
I created a loop with setTimeout function and it comes to a problem after 2nd or 3rd step it call's itself because it starts excecuting twice at the 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 variable value its 69, 68 and after that it starts decreasing variable value twice in one function call. I'm not calling function countDown() anywhere but from one place.
What could be the problem?
Edit: this code works now.
Upvotes: 4
Views: 6583
Reputation: 921
I'd recommend you to "sanitize" the timeouts by stopping previous one.
function interval() {
clearTimeout(intervalID);
intervalID = setTimeout(countDown, 1000);
}
However it looks like control of symptoms instead of sickness' cause. So it would be better to detect the cause of the issue.
Upvotes: 5