Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
Execution order in javascript

In the code below, the delay for 2 is 0secs, So why does it outputs 2 after 3 and not before it?

(function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 0); 
    console.log(3);
})();

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It will execute in the following matter:

1 3 2

setTimeout is implemented in a way it's meant to execute after a minimum given delay, and once the browser's thread is free to execute it. so, for an example, if you specify a value of 0 for the delay parameter and you think it will execute "immediately", it won't. it will, more accurately, run in the next event cycle (which is part of the event loop - concurrency model which is responsible for executing the code).

So, the printing of 1 and 3 will actually by pushed to the call stack and will execute immediately where as the setTimeout call back function will only be available to be pulled from the event queue to be picked in the next event loop tick.

Please read reason for delays longer then specified - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified

More about the JS event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

about 4 years ago · Juan Pablo Isaza Report

0

setTimeout() doesn't delay everything called after it; it only delays the function within. So it starts a timer for console.log(2), continues with the remaining code, console.log(3), and then runs the timeout function when the timer runs out.

about 4 years ago · Juan Pablo Isaza Report

0

This selfinvoked anonymous function declaration

function (function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 0); 
    console.log(3);
})();

is the same as if you've written

console.log(1);
setTimeout( console.log, 0, 2);
console.log(3);

and the order of logs will be the same - be it wrapped or unwrapped in an anonymous timed function - because it will be resolved during runtime, whereas the setTimeout declaration is a program, and will have to wait until the program starts execution. And it/this will be after the JITC has finished compiling your code.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!