Javascript在Node.js中是相同的

Javascript are these calls the same in Node.js?

本文关键字:Node js Javascript      更新时间:2023-09-26

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

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

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

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

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

例如:

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

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

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);

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