I have something like the following:
var myTimeout;
function delayStuffUntil( when ){
if( myTimeout) clearTimeout( myTimeout );
myTimeout = setTimeout( stuff, when - Date.now() );
}
delayStuffUntil
is going to get called a good deal, and it's likely that it will get called with the same value of when
several times in a row.
Is setTimeout
/clearTimeout
expensive enough that I should bother checking the current when
against my last value of when
(and only change timers if different)?
I thought about doing it, but the truth is that when
is a bit more fiddly to compare, and I figured premature optimization is the root of all evil, so I might be making work when I didn't need to.
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.
No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.
The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that. setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms). setTimeout() executes the passed function after given time.
The clearTimeout() function in JavaScript helps in clearing the timeout settings which are done for a session. It uses the variable name used in the setTimeout function and clears the settings using this as a reference.
setTimeout
and clearTimeout
by themselves aren't very expensive.
It's really the function "stuff" is what you have to worry about.
If stuff takes a long time to run then it might block the UI if it gets called too often.
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