2016-09-18 91 views
6
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代码被阻止?

+0

JavaScript并不是“多线程”;该功能以串行方式执行,而不是并行执行 –

回答

5

发生这种情况的原因是,无论何时您在setTimeout中传递function并调用它,传递的函数将根据所提供的延迟(毫秒)推入callBack队列。回调队列中的函数将按照它们推送的顺序逐个执行。因此,在这种情况下,您通过运行while循环来阻止存在于callBack队列中的function的代码流。因此第二次电话test需要10秒钟才能执行。

test(); //call 1 
callBack queue ----> [function(){ while(){} }] 

test(); //call 2 
callBack queue ----> [function(){ while(){} }, function(){ while(){} }] 

注意:回调队列将在调用堆栈中没有任何内容执行时开始执行。

给您最佳解答,Event Loop

+0

那么,while(){}'中的代码不会同时被执行? – lx1412

+0

@ lx1412是的,callBack队列中的函数将作为普通数组内部函数的正常执行来执行。逐个。 –

2

如果你想你有异步递归来取代你的同步while环非阻塞实现:

function test(x){ 
 
    setTimeout(function loop(now) { 
 
    (new Date()).getTime() < now.getTime()+2000 
 
    ? setTimeout(loop, 0, now) 
 
    : console.log('p', x); 
 
    },0, new Date()) 
 
} 
 

 
test(1); 
 
test(2);

相关问题