6

我想知道这两个代码块在Node.js中是否相同?

// Style 1
setTimeout(function () {
  console.log('hello');
}, 0);


// Style 2
console.log('hello');

由于上面我正在0超时,所以应该没有等待时间。console.log('hello');是否与不使用 setTimeout 直接调用相同?

4

2 回答 2

8

它们是不同的,第一个将函数添加到事件队列中,以便在当前执行路径完成后一旦有机会就可以执行。第二个将立即执行它。

例如:

console.log('first');

setTimeout(function(){
  console.log('third');
}, 0);

console.log('second');

这些打印的顺序是明确定义的,您甚至可以在打印“秒”之前做一些缓慢(但同步)的事情。保证在setTimeoutconsole.log('second');回调之前仍然会执行:

console.log('first');

setTimeout(function () {
  console.log('third'); // Prints after 8 seconds
}, 0);

// Spinlock for 3 seconds
(function(start){ while(new Date - start < 3000); })(new Date);

console.log('second'); // Prints after 3 seconds, but still before 'third'

// Spinlock for 5 seconds
(function(start){ while(new Date - start < 5000); })(new Date);
于 2013-09-13T06:56:04.557 回答
-3

严格来说,它们并不完全相同 - setTimeout 让浏览器有机会“赶上”它迫切需要完成的任何任务。但就我们通常所关心的而言,99% 的时间他们会做同样的事情。

于 2013-09-13T06:54:19.010 回答