Order of execution in Javascript

Given the below functions

function ME(){console.log("ME")};

function MYSELF(){window.setTimeout(function(){console.log("MYSELF")}, 0);}

function I(){
   return new Promise(function(resolve, reject){
     }, function(error){

If I supposedly call these functions sequentially as shown below:


Here is the order the javascript engine (Google’s V8 if chrome) takes precedence of executing it.

The output would be:

ME    // The ME() function outputs its result in the first place because it gets executed immediately even though it is being called in 3rd line, and the main reason being, it has no timeouts and nothing gets listed to the browser’s window Object

MYSELF   // The MYSELF() function outputs its result the second place even though it is being called in the 1st place AND it has a timeout function which is set to 0 seconds, because the timeout function is bound to the window object of the browser and it takes an extra roundtrip for the browser to get the event listened on its window object.

I   // The I() function outputs its result in the third place even though it is being called in the 2nd place, because it uses the asynchronicity feature using the Javascripts Native Promise function and also the resolve function of Promise gets called after a timeout of 5 seconds.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s