clearTimeout()
inside setTimeout()
method not working in JavaScript
var c = 0;
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
if (c == 5) {
clearTimeout(t);
}
t = setTimeout(function () {
timedCount()
}, 1000);
}
jsFiddle
clearTimeout()
inside setTimeout()
method not working in JavaScript
var c = 0;
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
if (c == 5) {
clearTimeout(t);
}
t = setTimeout(function () {
timedCount()
}, 1000);
}
jsFiddle
Share Improve this question edited Mar 15, 2013 at 17:27 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Mar 15, 2013 at 17:24 Kathirvel ShanmugasundaramKathirvel Shanmugasundaram 1531 gold badge1 silver badge11 bronze badges 2-
8
It does "work", but your logic is incorrect. After you called
clearTimeout
you are callingsetTimeout
again. Instead of callingclearTimeout
you should just exit the function. – Felix Kling Commented Mar 15, 2013 at 17:26 - See here as @Felix pointed jsfiddle/SEGtY/7 – Rodrigo Siqueira Commented Mar 15, 2013 at 17:28
2 Answers
Reset to default 9You need to prevent the rest of the code of executing, actually you are re-declaring t
after clearing the setTimeout
. Fiddle
var c = 0;
var t;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
if (c == 5) {
clearTimeout(t);
return false;
}
t = setTimeout(timedCount, 1000);
}
Or just use the else
statement:
if (c == 5) {
clearTimeout(t);
// do something else
}else{
t = setTimeout(timedCount, 1000);
}
There will never be a timeout to clear when you call clearTimeout
as the last one will have already fired and the next one won't have been set yet.
You want to change your logic so that if (c !== 5) { setTimeout(etc etc) }