Forum Moderators: open

Message Too Old, No Replies

setTimeout minimal value in reccurring action

         

warp_fr

10:50 am on Jan 22, 2005 (gmt 0)

10+ Year Member



Is there any limitation, like sucking too much from the CPU, in setting a very small value in milliseconds for setTimeout() for a reccuring action like in the following exemple :

function doSomething() {
if (document.images.myPic.complete) {
...
clearTimeout(timer);
} else {
timer = setTimeout('doSomething()', 1);
}
}

Bernard Marx

1:43 pm on Jan 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes (ish).

Morten Wong did a good study on the subject some time ago:
[webreference.com ]

It seems that it's actually pointless setting a timer value below a certain figure (25-40 ms?), because you won't get a faster rate anyway - with a single timer.

I'd guess that it may be better, cpu-wise, to use a single setInterval, rather than setting a setTimeout that calls a setTimeout, that ...

Another proposition could be that, since the 'traditional' timer use requires the runtime compilation of a string of code, it should presumeably be more efficient to use the alternative - a function reference.

Referencing the image via a chain from the document is inefficient too. All told, none of this really matters, but here's an attempt to put all the above ito practice anyway (It keeps the timer variable out of the global namespace too).


doSomething('myPic')

function doSomething(imgName)
{
function test(){
if (img.complete) clearTimeout(timer);
}
var img = document.images[imgName];
var timer = setInterval(test, 25);
}

warp_fr

1:34 pm on Jan 23, 2005 (gmt 0)

10+ Year Member



Merci Bernard! ;-)
It's been helpfull. I believe you mean in your exemple :

if (img.complete) clearInterval(timer);

I will redesign all my functions using setInterval() instead and passing by reference to see how it improves the whole process.

warp_fr

7:55 pm on Jan 24, 2005 (gmt 0)

10+ Year Member



Considering :
timer = setInterval(test, 25);

Is this the right way to go to test if interval has been set for test():
if (typeof timer!= 'undefined') {

I can find what kind of value is assigned to timer when using setInterval(), any idea?

Bernard Marx

10:30 pm on Jan 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this:

timer = setTimeout(function(){alert(typeof timer+': '+timer)},1000)

It the same for

setInterval
. The value returned by the timer function is a plain ol' number primitive.

This will remain even if you clear the timer, so if you need to 'know' that it has been cleared, then you'll also have to set the variable to something (eg: null) manually when you clear it.

if (typeof timer!= 'undefined')

That's fine, but, with Javascript's boolean evaluation rules, you could also do this:

if (window.timer)

(but read prev. paragraph again)