Books

Sunday, January 26, 2014

Effect of Setting setTimeout to 0 and Explanation of JavaScript's Single Threaded, Non Blocking I/O, Async Event Driven Model

If you have two functions:

var f1 = function () {    
   setTimeout(function(){
      console.log("f1", "First function call...");
   }, 0);
};

var f2 = function () {
    console.log("f2", "Second call...");
};

and then you call them:

f1();
f2();

Checking your console, this is what you see:


If you were expecting to see "f1 First function call..." first, then you are not alone. This is what I initially expected based on my assumption that having a setTimeout set to 0 milliseconds, well mean, execute right away. Apparently this is not how things work.

This post is about how this unexpected behaviour led me into having a refresher of some of the core concepts regarding how JavaScript executes.