Which option is better to execute window.setTimeout and why?
Option A:
window.setTimeout(somefunc,0);
Option B:
window.setTimeout(somefunc,n); //n may be any number >0
Thanks.
Which option is better to execute window.setTimeout and why?
Option A:
window.setTimeout(somefunc,0);
Option B:
window.setTimeout(somefunc,n); //n may be any number >0
Thanks.
Option A will simply call somefunc
with the additional overhead of needlessly calling setTimeout
(since your second parameter means 0 milliseconds of delay). Option B is for if you intend to have a delay prior to the execution of somefunc
. Could you elaborate a bit please, or does this answer your question?
It depends on what you want to do.
setTimeout(somefunc,0)
is not so different with just calling somefunc
(but I guess .setTimeout(somefunc,0)
will finish current block first and then called somefunc
)
If you need to wait browser rendering, and run somefunc
after that, use window.onload
or jQuery's $(document).ready
window.setTimeout(somefunc,0);
will run somefunc right away (but won't wait for a return value before continuing)
window.setTimeout(somefunc,n);
will wait n milliseconds before running somefunc (but won't wait for it to start or return before continuing)
or if you call somefunc()
without the timeout it will run somefunc but wait for it to finish before continuing.
consider setTimeout to be like "starting" a new thread.
The thing about a timeout or an interval, they always wait for the current thread to run out before they execute their own function- even if you put it in the first line.
var color='white';
setTimeout(function(){alert(color+' from timeout')}, 0);
for(var i=0;i<100001;++i){
if(i=100000)alert(color='green');
}
alert(color='red')
I recall having some browser issues when using setTimeout (func, 0)
so now I do setTimeout (func, 1)
whenever I want to have the shortest delay. Note that for most (all?) browsers the real shortest delay is some number n > 1
(definately n > 0
and probably n < 50
).
Which browser I was having issues with I don't remember.