0

according to MDN

var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);

as you can see:

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

the result is fristly '1' and then '2'.

   setTimeout(alert(2), 0);
   alert(1);

however,the result is fristly '2' and then '1'.

what causes the difference?

  • in the second case `alert` is executed immediately and no timeout is being set. – pawel Jul 31 '16 at 11:47
  • The JS is resolving ```alert(2)```, as it may return a function which you intend to timeout. The first is a legitimate timeout, which will run after the current execution queue. – horyd Jul 31 '16 at 11:47
  • BTW there's one more option for you to try: `setTimeout("alert(2)", 0);` – pawel Jul 31 '16 at 11:48
  • By "code" they mean a code string, i.e. `"alert(2)"`. What you were passing is just the result of calling `alert` immediately. – Bergi Jul 31 '16 at 11:51
  • Does you mean that as long as the code is not a code string, it will be executed firstly regardless of ` delay ` – 落叶无痕 Jul 31 '16 at 12:18

1 Answers1

1

In the case of

setTimeout(alert(2), 0);
alert(1);

First alert(2) is executed and its return value (i.e. undefined) is passed to setTimeout function, while in the first example a function is passed to the setTimeout function.

Also have a look at: Why is setTimeout(fn, 0) sometimes useful?

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129