Georgy
Georgy

Reputation: 2462

How is execution queue generated in JavaScript?

Consider this simple example:

console.log('Start');

setTimeout(function() {
  console.log('First timeout');
}, 100);

setTimeout(function () {
  console.log('Second timeout');
}, 2000);

var time = Date.now();
for (var i = 0; i < 2000000000; i++) {
  var temp = i * i * Math.sqrt(i);
  temp = temp + temp;
}
console.log(Date.now() - time);

setTimeout(function () {
  console.log('Third timeout');
}, 50);

console.log('End');

The output is:

Start
1219
End
First timeout
Third timeout
Second timeout

What makes me think of the way the execution queue (stack?) is generated. Am I right that JavaScript intepreter checks the code first, generates the queue, and then starts the execution, adding functions from timeouts to the end of the queue when timeout time passes (so we have pregenerated execution queue which updates during the execution and dynamically generated timeout list)?

Upvotes: 1

Views: 386

Answers (1)

Lavi Avigdor
Lavi Avigdor

Reputation: 4182

JavaScript is single-threaded. The timeout calls are pushed to the event loop, thus they are executed after all the main flow calls.

console.log('Start');  **-> Printed #1 **

setTimeout(function() {
  console.log('First timeout');    **-> Pushed to eventloop #1 **
}, 100);

setTimeout(function () {
  console.log('Second timeout');**-> Pushed to eventloop  #3 !! **
}, 2000);

var time = Date.now();
for (var i = 0; i < 2000000000; i++) {
  var temp = i * i * Math.sqrt(i);
  temp = temp + temp;
}
console.log(Date.now() - time); **-> Printed #2 **

setTimeout(function () {
  console.log('Third timeout');  **-> Pushed to eventloop #2 !!**
}, 50);

console.log('End'); **-> Printed #3 **

Note: "Third timeout" was pushed to the event loop #2 instead of #1 even thougt it has a 50ms vs 100ms (of first) since it was processed after you lengthy for loop, which took enough time for the first's timeout to be reached.

EventLoop explained: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Upvotes: 2

Related Questions