事件循环是由一系列阶段构成的setTimeout()
会被放在timers
阶段setImmediate()
会被放在check
阶段process.nextTick()
会在当前阶段结束后紧跟着执行
来判断如下代码的用node.js执行后输出顺序
setTimeout(()=>console.log('setTimeout'),0)
setImmediate(()=>console.log('setImmediate'))
/*
output:
setTimeout
setImmediate
*/
//或
/*output
setImmediate
setTimeout
*/
可以发现执行两个计时器的顺序是非确定性的。
因为不在 I/O 周期(即主模块)内的运行的脚本,它受进程性能的约束。
如果把这两个函数放入I/O循环内调用,setImmediate
总是会先被调用
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => {
console.log('setTimeout');
}, 0);
setImmediate(() => {
console.log('setImmediate');
});
});
/*output
setImmediate
setTimeout
*/
把这两个函数放在setTimeout
或setImmediate
里调用,setImmediate
也总是会被先调用
setImmediate(()=>{
setTimeout(()=>console.log('setTimeout'),0)
setImmediate(()=>console.log('setImmediate'))
})
/*output
setImmediate
setTimeout
*/
setTimeout(()=>{
setTimeout(()=>console.log('setTimeout'),0)
setImmediate(()=>console.log('setImmediate'))
},0)
/*output
setImmediate
setTimeout
*/
关于process.nextTick()的执行顺序
setTimeout(()=>{
setTimeout(()=>console.log('setTimeout'),0)
setImmediate(()=>console.log('setImmediate'))
process.nextTick(()=>console.log('nextTick'))
},0)
/*output
nextTick
setImmediate
setTimeout
*/
setTimeout(() => {
setTimeout(() => console.log("setTimeout"), 0);
setImmediate(() => {
process.nextTick(() => console.log("nextTick"));
console.log("setImmediate");
});
}, 0);
/*output
setImmediate
nextTick
setTimeout
*/
setTimeout(() => {
setTimeout(() => {
process.nextTick(() => console.log("nextTick"));
console.log("setTimeout");
}, 0);
setImmediate(() => console.log("setImmediate"));
}, 0);
/*output
setImmediate
setTimeout
nextTick
*/