9
var timeout = setTimeout(function(){
     console.log("I'm message from timeout");
},0);

console.log("I'm message from outside timeout");

//1. I'm message from outside timeout
//2. I'm message from timeout

Why the inner instructions don't execute first, despite setting setTimeout time on 0? I use various times including 0/null and I'm wondering how to both retain setTimeout object and execute its instructions with the flow.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Paweł
  • 4,238
  • 4
  • 21
  • 40
  • 3
    setTimeout *always* is deferred until the *next* "execution time" of JavaScript. A value of 0/null does not change this (and is treated as a value of 5 in modern browsers). – user2864740 Apr 28 '16 at 03:35
  • 3
    I wrote a long answer here: http://stackoverflow.com/questions/32580940/cleartimeout-necessary-after-settimeout-with-0ms/32591948#32591948 and there are likely many other related questions – user2864740 Apr 28 '16 at 03:38
  • http://stackoverflow.com/questions/9647215/what-is-minimum-millisecond-value-of-settimeout?lq=1 – user2864740 Apr 28 '16 at 03:40
  • You should check this out: https://www.youtube.com/watch?v=8aGhZQkoFbQ – Crisoforo Gaspar Apr 28 '16 at 03:52

1 Answers1

7

Javascript code runs only on one thread. setTimeout schedules a function to run later. So in js when all currently running code finish its execution , event loop will look for any other event. So setTimeout( .. 0) will make code run after the current loop.

console.log("I'm message from outside timeout"); will be first scheduled to executued. As soon as it finish the setTimeout will be executed

So bottom line setTimeout(myfunction ,0) will run myfunction 0ms after currently executing function. & in your case the current execution loop is

console.log("I'm message from outside timeout");

If you add another console.log("I'm message from outside timeout1"); so current event loop will first log

I'm message from outside timeout
I'm message from outside timeout1

before starting setTimeout function.

NOTE setTimeout has a minimum timeout of 4ms . You can look at this Stackoverflow thread to know more about it

brk
  • 48,835
  • 10
  • 56
  • 78
  • 2
    The way you explain the order is confusing. `setTimeout` itself is executed before the `console.log`, only the function passed *to* it is scheduled. – Felix Kling Apr 28 '16 at 04:07
  • 4
    Regarding "*…minimum timeout of 4ms*", that is not necessarily true. The current [*WHATWG spec*](https://html.spec.whatwg.org/multipage/webappapis.html#timers) says "*… after five such nested timers, however, the interval is forced to be at least four milliseconds*". So the minimum delay is whatever the implementation has it set to. – RobG Apr 28 '16 at 04:08
  • Yes, the "4ms minimum" is very misleading. Here's a fiddle to verify: http://jsfiddle.net/pgjbn8o5/ – Jacksonkr Oct 02 '18 at 13:15