Abhishek
Abhishek

Reputation: 351

Timeout is not working as expected

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.

Upvotes: 1

Views: 618

Answers (3)

L.Wonbae
L.Wonbae

Reputation: 131

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

Upvotes: 2

Nemani
Nemani

Reputation: 784

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

Upvotes: 0

Sachin
Sachin

Reputation: 2148

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 ..

Upvotes: 0

Related Questions