0

While trying to read Async javascript book(Perhaps I am not qualify to read this book yet), I saw below example:

for (var i = 1; i <=3; i++ ) {
   setTimeout(function() { console.log(i); }, 0);
};

And I cannot understand the life of me why answer is 4,4,4

I try to understand what book is mentioning but I fail to understand what they are refering to . Can someone put this in more layman's term?

UPDATE(after I got all the comments).. To help myself understand I added some console logs for those who are newbie like me and might need help w/ this same issue. This is great site! I will be back for much more..

for ( var i = 1; i <= 3; i++ ) {
    console.log(i);
    setTimeout( function() { console.log(i); }, 0 );
    console.log("still", i);
};
console.log('jo');

1
still 1
2
still 2
3
still 3
jo
4
4
4
[Finished in 0.1s]
user3502374
  • 781
  • 1
  • 4
  • 12

1 Answers1

0

The settimeout is put onto a list of Items to complete when the browser has time to. The browser can only read that list once it is done with all the other work it has to do.

Explaining it a different way: JavaScript is single threaded, it can only do one thing a a time and the list of settimeouts can only be completed when no code is being run

Marc Guiselin
  • 3,442
  • 2
  • 25
  • 37