Just found this code-snippet in our application. I am wondering if the first line is superfluous -- does one need to call clearTimeout on a variable if it is immediately overwritten? Or is there some condition I should be aware of?
function Countdown() {
clearTimeout(sessionTimeoutHandle);
sessionTimeoutHandle = setTimeout(function () { countdownHandler() }, MILLISECONDS);
}
My hunch is "Yes, you need to call clearTimeout" because I can't think of why the clearTimeout method would exist if it was OK to just set the timeout variable to null.
I suppose the better question is:
var timeoutHandler = setTimeout(countdownHandler, MILLISECONDS);
timeoutHandler = setTimeout(countdownHandler, MILLISECONDS);
Do I now have two functions waiting to fire in approximately MILLISECONDS, or just one?
clearTimeout() is a function which helps in clearing out the previously set time out time which was set by making use of the setTimeout() function which creates an ID value and this value, in turn, helps in clearing the time out which is sent as a parameter to JavaScript clearTimeout().
You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.
A setTimeout timer must be cleared and handle properly, otherwise, you may experience adverse side effects in your code. To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout().
The global clearTimeout() method cancels a timeout previously established by calling setTimeout() .
Your call to setTimeout returns an integer to id it, so that you have a reference to it when you want to clear it. So overwriting the variable doesn't clear the timeout it just overwrites your reference to it's id. If you overwrite the reference you can no longer clear the earlier one :-(
You'll use clearTimeout as Niko says - to stop the callback from firing.
illustration:
var t = setTimeout(ch, 1000, "first timeout");
t = setTimeout(ch, 1500, "second timeout");
clearTimeout(t); // this will only clear the second timeout
t = setTimeout(ch, 2000, "third timeout");
function ch(s){
console.log(s);
}
I hope this is some help.
No, you only need to call it if you actually need to clear it.
If this is the only code using that variable, then there should be no need.
FYI, it looks like you could shorten the code a bit...
function Countdown() {
clearTimeout(sessionTimeoutHandle);
sessionTimeoutHandle = setTimeout(countdownHandler, MILLISECONDS);
}
Nothing was gained with the anonymous function.
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