process.nextTick与setTimeout递归调用区别
qufei1993 opened this issue · 5 comments
qufei1993 commented
问题出自 ElemeFE
以下是我的理解,如有不对,请多多指正!
process.nextTick属于微任务,是在当前执行栈的尾部,EventLoop之前触发,下面两个都是递归调用,test1中process.nextTick,是在当前执行栈调用,是一次性执行完,相当于 while(true){},主线程陷入了死循环,阻断IO操作。
test2方法中,setTimeout属于宏任务,在任务队列中,同样也是递归不是一次性的执行而是在多次Loop,不会阻断IO操作,另外注意setTimeout有一个最小的时间4ms。
function test1() {
process.nextTick(() => test());
}
function test2() {
setTimeout(() => test(), 0);
}
process.nextTick将会阻塞IO,setImmediate不会输出的情况:
{
function test() {
return process.nextTick(() => test());
}
test();
setImmediate(() => {
console.log('setImmediate');
})
}
下面使用setTimeout不会造成IO阻塞,会输出 setImmediate的情况:
function test() {
setTimeout(() => test(), 0);
}
test()
setImmediate(() => {
console.log('setImmediate');
})
// setImmediate
闲暇之余会写一些技术博客,感兴趣的的可以star下 https://github.com/Q-Angelo/summarize
Lellansin commented
很准确
luckyscript commented
mark
quanru commented
+1
sd0xdev commented
Nice
shanzhangf123 commented
这是来自QQ邮箱的假期自动回复邮件。
您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。