2

Does

setTimeout(function () { /*logic*/ }, 0);

Really makes the function to be asynchronous?

George
  • 36,413
  • 9
  • 66
  • 103
Abhishek Subradeep
  • 296
  • 1
  • 5
  • 20
  • 5
    [Why is setTimeout(fn, 0) sometimes useful?](http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) – Vucko May 15 '13 at 10:46
  • 1
    What it really does is pause javascript execution to allow for the other browser events (such as loading the DOM) to catch up. See: http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – KernelPanik May 15 '13 at 10:47
  • @KernelPanik That is not exactly true. The execution does not get paused. The function is queued on the browser's Event Queue. – Christoph May 15 '13 at 11:45
  • @Abhishek: What exactly is your understanding of "*asynchronous*"? The answer could be both yes and no :-) – Bergi May 15 '13 at 11:48

4 Answers4

4

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.

Christoph
  • 50,121
  • 21
  • 99
  • 128
1

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

Community
  • 1
  • 1
Sirko
  • 72,589
  • 19
  • 149
  • 183
0

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.

michael
  • 4,427
  • 6
  • 38
  • 57
0

Its a bit difficult to explain whole javascript timer thing. May be this will help you.

John Resig Blog: How does Javascript timers work

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168