我想知道这两个代码块在Node.js中是否相同?
// Style 1
setTimeout(function () {
console.log('hello');
}, 0);
// Style 2
console.log('hello');
因为我在上面将超时设置为0
,所以不需要等待时间。这与直接调用console.log('hello')
且不使用setTimeout是否相同?
我想知道这两个代码块在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');
。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);
process.nextTick(...)
是比setTimeout(..., 0)
更高效的替代方案,因为它不涉及计时器调度的开销。 - Matt Patenaude