Node.js中的setImmediate()与process.nextTick
简单说,process.nextTick是在当前代码执行完毕后立即执行,setImmediate是加入到轮询,空闲后立即执行.
测试结论:
process.nextTick >> setTimeout(handler,0) , setImmediate >> setTimeout(handler, n)
注: setTimeout(handler,0) 与 setImmediate的顺序未深入比较.
上代码:
var a = 1;
console.log(a);
setImmediate(function() {
console.log('-----------setImmediate----------');
console.log(a);
});
a=2;
setTimeout(function() {
console.log('-----------settimeout 0----------');
console.log(a);
},0);
a=3;
setTimeout(function() {
console.log('-----------settimeout 2000----------');
console.log(a);
},2000);
a=4;
setTimeout(function() {
process.nextTick(function() {
a=6;
console.log('-----------process.nextTick----------');
console.log(a);
});
console.log('-----------settimeout 1000----------');
console.log(a);
},1000);
a=5;
process.nextTick(function() {
console.log('-----------process.nextTick----------');
console.log(a);
});
执行结果:
1
-----------process.nextTick----------
5
-----------settimeout 0----------
5
-----------setImmediate----------
5
-----------settimeout 1000----------
5
-----------process.nextTick----------
6
-----------settimeout 2000----------
6