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
This is due to when a function is executed as a parameter to setTimeout , the execution context is different to the execution context of the function! Now this will print out undefined because the this keyword is executed in the context of the setTimeout function and is therefore not defined.
You need to pass the amount of time to wait for in milliseconds , which means to wait for one second, you need to pass one thousand milliseconds . To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.
The global clearTimeout() method cancels a timeout previously established by calling setTimeout() . If the parameter provided does not identify a previously established action, this method does nothing.
setTimeout(() => clearTimeout(id), y_mili); it'll clear the timeout with the id at that time, as you evaluate id when the timeout is done, and not when it get's started.
You 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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With