Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is setTimeout/clearTimeout expensive?

Tags:

javascript

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.

like image 763
rampion Avatar asked Jan 30 '12 23:01

rampion


People also ask

Should I use 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.

Is setTimeout heavy?

No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.

What is setTimeout and clearTimeout?

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.

Why do we use clearTimeout?

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.


1 Answers

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.

like image 154
KDV Avatar answered Sep 20 '22 07:09

KDV