Does
setTimeout(function () { /*logic*/ }, 0);
Really makes the function to be asynchronous?
Does
setTimeout(function () { /*logic*/ }, 0);
Really makes the function to be asynchronous?
No, it does not make the function asynchronous - if the function takes some time it will still block the thread.
However, setTimeout
puts this function onto the Browser's Event Queue. So it will be executed after all other events which are already on that queue and are waiting to get executed (and would be executed after your scriptblock is finished if you weren't using the timeout).
To be precise, setTimeout(xxx,0)
does make no sense, the minimum delay is 4ms, as stated in the spec.
Altogether the timing is a bit more complex than I explained here, but this might be sufficient as toplevel explanation;) For more info, check John Resig's Article.
No it does not.
It just places the function on the event queue with the given delay (here a delay of zero). If there are any other functions currently queued up for execution, it gets placed behind them and has to wait until those (including the currently active) functions are executed.
To test this, you could do something like ethis
console.log( 'start' );
setTimeout(function () {
console.log("timeout");
}, 0);
// some very long running code
console.log( 'end' );
You will still get the output:
start
end
timeout
Not exactly
console.log("1");
setTimeout(function () {
console.log("2");
}, 0);
console.log("3");
You'll probably see the output...
1
3
2
The timeout will not block the execution of the code but ALL browsers enforce a minimum timeout delay.
Its a bit difficult to explain whole javascript timer thing. May be this will help you.