1

console.time("Time");
var i=0;
setTimeout(function(){console.log("Timeout...")},500);

while(true){
  if(i==1000000000){
    console.timeEnd("Time");
    console.log("whileloop breaking...");
    break;
  }
  else{i++;}
}

In this code i'm trying to print Timeout in console after 0.5 second, and there is a while loop which terminates after a time of around 2 seconds which i'm showing through logging the time spent. I expected Timeout to print first as it completes in 0.5 seconds and the whileloop breaking should print which takes more time, but it's printing whileloop breaking first and then going for Timeout...can anyone explain stack trace or flow of this code.

Andree Wille
  • 928
  • 1
  • 9
  • 22
Abhishek
  • 351
  • 1
  • 3
  • 18
  • 6
    Javascript is single threaded. The timeout can't run until the while loop finishes. – RobG Aug 29 '17 at 08:45
  • so how does it keep track like to go back for timeout only after whileloop execution?is it through stack? – Abhishek Aug 29 '17 at 08:47
  • The timeout is scheduled to run in .5 seconds. The scheduler won't check until it's free to run it. – RobG Aug 29 '17 at 08:49
  • See [*How does setTimeout work in Node.JS?*](https://stackoverflow.com/questions/5849106/how-does-settimeout-work-in-node-js), noting that Node.js goes its own way a bit. – RobG Aug 29 '17 at 08:51
  • Thank you,Clears my doubt very well – Abhishek Aug 29 '17 at 09:15

3 Answers3

2

First, i do not speak English very well. but I want to help you

The browser is a single thread event queue. If the first task is running, then all events will be held

look at your code

You declared setTimeout However, this setTimeout runs in 0.5s

But you can not execute setTimeout after 0.5seconds because whileloop has only one thread in a single-threaded browser

I prepared a link for you

Wrestling with the Browser Event Queue

Concurrency model and Event Loop

L.Wonbae
  • 131
  • 8
0

As @RobG commented - "Javascript is single threaded. The timeout can't run until the while loop finishes."

But if you want to print Timeout first and then whileloop breaking in your code then try this--

console.time("Time");
var i=0;
//setTimeout(function(){console.log("Timeout...")},500);
setTimeout(console.log("Timeout..."),500);

while(true){
  if(i==1000000000){
    console.timeEnd("Time");
    console.log("whileloop breaking...");
    break;
  }
  else{i++;}
}

I have just removed function(){} from setTimeout ..

Sachin
  • 2,152
  • 1
  • 21
  • 43
  • how come this is printing Timeout 1st,can u explain a bit please – Abhishek Aug 29 '17 at 09:16
  • here the Timeout will print without waiting for timer to expire, try with larger timer value – Nemani Aug 29 '17 at 09:32
  • Thank you,That i understood,but when it is inside the function it is waiting along the time,but when console.log is called its printing immediately...why? – Abhishek Aug 29 '17 at 09:37
  • Read this : "In JavaScript execution there is **Context (which ECMA 5 breaks into LexicalEnvironment, VariableEnvironment and ThisBinding) and Process (a set of statements to be invoked in sequence)**. Declarations contribute to the VariableEnvironment when the execution scope is entered." Ref - https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ &&& http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – Sachin Aug 29 '17 at 09:40
  • what does this links has to do with your answer above? – Nemani Aug 29 '17 at 09:44
  • 1
    @Abhishek the difference is between **function call** and a **reference to a function**, when you pass console.log() as an argument, its a function call, so it executes when starting timer and JS expect this function call to return a function reference (but it does not return anything here) so nothing will be executed on timer expiry. – Nemani Aug 29 '17 at 09:47
  • Thank you ,Understood verywell :) – Abhishek Aug 29 '17 at 09:55
0

Here is the best way to visualize whats happening when you run above code:

http://latentflip.com/loupe/?code=Y29uc29sZS50aW1lKCJUaW1lIik7DQp2YXIgaT0wOw0Kc2V0VGltZW91dChmdW5jdGlvbigpe2NvbnNvbGUubG9nKCJUaW1lb3V0Li4uIil9LDUwMCk7DQoNCndoaWxlKHRydWUpew0KICBpZihpPT0xMDAwMDAwMDAwKXsNCiAgICBjb25zb2xlLnRpbWVFbmQoIlRpbWUiKTsNCiAgICBjb25zb2xlLmxvZygid2hpbGVsb29wIGJyZWFraW5nLi4uIik7DQogICAgYnJlYWs7DQogIH0NCiAgZWxzZXtpKys7fQ0KfQ0KIA%3D%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D

Lets understand whats happening in the code

    console.time("Time");
        var i=0;
        //here a callback is registered and should be called when timer expires
        setTimeout(function(){console.log("Timeout...")},500);

        //since settimeout is async in nature, main thread continues 
    //to execute new line of code i.e. while loop
        // After 500 ms when timer expires, it puts the callback in event queue, 
    // the callback will be executed as soon as it sees the main thread free, but since 
//while loop is running on main thread for 2sec, the main thread will be free //only after 2 sec (or while loop) finishes.
        while(true){
          if(i==1000000000){
            console.timeEnd("Time");
            console.log("whileloop breaking...");
            break;
          }
          else{i++;}
        }
        // as there is no code to be executed now, main thread takes new task from 
        // event Queue, in this case the new task is callback from settimeout.

I hope this helps you to understand a little on settimeout

Nemani
  • 778
  • 5
  • 12