2017-08-29 108 views
0

超时未按预期

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++;} 
 
}

在这段代码中我试图在0.5秒之后打印超时控制台,并有一个while循环它的时间后终止大约2秒钟,我通过记录所花时间显示。我预计超时,首先打印,因为它完成在0.5秒和while循环打破应打印,需要更多的时间,但它的打印while循环打破第一,然后去为超时 ...任何人都可以解释堆栈跟踪或代码流。

+6

JavaScript是单线程的。超时无法运行,直到while循环结束。 – RobG

+0

那么它是如何跟踪回到超时执行while循环之后?是通过堆栈? – Abhishek

+0

超时时间预计在0.5秒内运行。调度程序不会检查,直到它可以运行它为止。 – RobG

回答

0

这里是想象发生了什么的最好方式,当你运行上面的代码:

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

让我们明白什么代码发生

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. 

我希望这可以帮助你了解一点点settimeout

+0

谢谢verymuch – Abhishek

+1

@Ahishek我的荣幸:) – Nemani

+0

@Abhishek,upvote将帮助:) – Nemani

0

As @RobG评论说:“Javascript是单线程的,直到while循环结束才能运行超时。”

但是,如果你想打印超时while循环打破在你的代码,然后尝试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++;} 
 
}

我刚才删除function(){}setTimeout ..

+0

这是怎么来的打印Timeout 1st,请你解释一下吧 – Abhishek

+0

这里Timeout打印不用等待定时器过期,试用大定时器值 – Nemani

+0

谢谢,那我明白了,但是当它在它正在等待的函数内时,但是当console.log被立即调用时......为什么? – Abhishek

2

首先,我不会说英语很好。 但我想帮你

浏览器是单线程事件队列。 如果第一个任务正在运行,则所有事件将被

看看你的代码

您申报的setTimeout 月举行

,该setTimeout的运行在0.5秒

但0后无法执行的setTimeout 。5秒 因为while循环中只有一个单线程的浏览器

线程我准备了一个链接,你

Wrestling with the Browser Event Queue

Concurrency model and Event Loop

+0

谢谢你Wonbae李,​​没有问题与你的英语......我明白了 – Abhishek