rampion rampion - 3 months ago 29
Javascript Question

is setTimeout/clearTimeout expensive?

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.

KDV KDV
Answer

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.