0

I have a function like this:

var a = function () {
    setTimeout(function () {
        alert(2);
    }, 0);
    alert(1);
}

a();

the result is alert 1 first, then alert 2

But I think, though alert(2) is in the setTimeout, but it executes immediately,because the delay is 0

Why is the alert(1) executed first?

Matt Cain
  • 5,638
  • 3
  • 36
  • 45
hh54188
  • 14,887
  • 32
  • 113
  • 184

3 Answers3

1

If you wan't it to execute immediately just remove the setTimeout, you are getting alert(1) first because setTimeout has a minimum value see here. So when you set it to 0 it uses the minimum value depending on browser.

Community
  • 1
  • 1
Barış Uşaklı
  • 13,440
  • 7
  • 40
  • 66
1

setTimeout has a default delay that will cause it to execute after alert(1) has executed.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
0

As other also noted, setTimeout() has a minimum timeout of 4ms.

More importantly though, even if it had a real time-out of 0ms, it wouldn't fire first either. That's because Javascript is single-threaded (disregarding web-workers).

alert(2) fires last because anything set in setTimeout() will only fire after the current Javascript execution is done. In other words: setTimeout() actions are placed at the end of the execution stack.

So the current function execution will finish first (running the alert(1)) and only then the alert(2) gets executed.

That's also the reason that setTimeout only guarantees that the code within it is executed after the specified time, not at the exact time.

See http://ejohn.org/blog/how-javascript-timers-work/ for a great overview.

Willem Mulder
  • 12,974
  • 3
  • 37
  • 62
  • Could the downvoter please revoke his vote? Or specify what's wrong with the answer? Because I'm pretty sure it's 100% correct. – Willem Mulder Jun 14 '13 at 08:47