- function test(){
- setTimeout(function(){
- var now=new Date();
- while((new Date()).getTime() < now.getTime()+5000){ }
- console.log('p')
- },0);
- }
- test();
- test(); //it takes 10 seconds,the second test function runs after the first finished.
谁可以向我解释它是如何工作的?
解决方法
发生这种情况的原因是,每当您在setTimeout内部传递函数并调用它时,传递的函数将根据提供的延迟(以毫秒为单位)推送到callBack队列. callBack队列中的函数将按照它们推送的顺序逐个执行.因此,在您的情况下,您通过运行while循环来阻止callBack队列中存在的函数的代码流.因此,第二次测试调用需要10秒才能执行.
- test(); //call 1
- callBack queue ----> [function(){ while(){} }]
- test(); //call 2
- callBack queue ----> [function(){ while(){} },function(){ while(){} }]
注意:当调用堆栈中没有任何内容要执行时,回调队列将开始执行.
最好的阅读,Event Loop.