Javascript是这些调用在Node.js中是一样的吗?

Nam*_*yen 6 javascript node.js express

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

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


// Style 2
console.log('hello');
Run Code Online (Sandbox Code Playgroud)

从上面开始我0超时,应该没有等待时间.它是否与console.log('hello');不使用setTimeout直接调用相同?

Pau*_*aul 8

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

例如:

console.log('first');

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

console.log('second');
Run Code Online (Sandbox Code Playgroud)

这些打印的顺序是明确定义的,你甚至可以在打印'秒'之前做一些缓慢(但同步)的事情.保证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);
Run Code Online (Sandbox Code Playgroud)

  • @NamNguyen是的,对于node.js和Web浏览器都是如此. (2认同)