Forum Moderators: open
function doSomething() {
if (document.images.myPic.complete) {
...
clearTimeout(timer);
} else {
timer = setTimeout('doSomething()', 1);
}
}
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);
}
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)