setImmediate该方法用来把一些需要长时间运行的操作放在一个回调函数里,在浏览器完成后面的其他语句后,就立刻执行这个回调函数。
setImmediate是宏任务,优先级是比定时任务低的。除非在定时任务中。
测试代码:
setImmediate(function(){
console.log("setImmediate");
setImmediate(function(){
console.log("setImmediate-setImmediate");
});
setTimeout(function(){
console.log("setImmediate-setTimeout");
});
process.nextTick(function(){
console.log("setImmediate-nextTick");
});
});
setTimeout(function(){
console.log("setTimeout");
setTimeout(function(){
console.log("setTimeout-setTimeout");
});
setImmediate(function(){
console.log("setTimeout-setImmediate");
});
process.nextTick(function(){
console.log("setTimeout-nextTick");
});
});
process.nextTick(function(){
console.log("nextTick");
setImmediate(function(){
console.log("nextTick-setImmediate");
});
setTimeout(function(){
console.log("nextTick-setTimeout");
});
process.nextTick(function(){
console.log("nextTick-nextTick");
});
});
结果如下:
nextTick
nextTick-nextTick
setTimeout
nextTick-setTimeout
setTimeout-nextTick
setImmediate
nextTick-setImmediate
setTimeout-setImmediate
setImmediate-nextTick
setTimeout-setTimeout
setImmediate-setTimeout
setImmediate-setImmediate
解析:
// 第一圈
nextTick //优先执行微任务
nextTick-nextTick //优先执行微任务,直到完成所有微任务
setTimeout //接下来执行到时间的定时任务
nextTick-setTimeout //直到完成所有定时任务
setTimeout-nextTick //完成所有定时任务,后才会执行完所有新增的微任务
setImmediate //最后执行宏任务
nextTick-setImmediate //直到完成所有宏任务
setTimeout-setImmediate //直到完成所有宏任务
// 第二圈
setImmediate-nextTick //优先执行微任务
setTimeout-setTimeout //接下来执行到时间的定时任务
setImmediate-setTimeout //直到完成所有定时任务
setImmediate-setImmediate //最后执行宏任务