扫码关注官方订阅号
在看深入浅出nodejs定时器的内容时,看到这样的一段代码运行了一下,输出如下:
好像跟想象的不太一样??查了一下好像‘强势插入’应该在‘setImmediate延迟执行1’和‘setImmediate延迟执行2’之间输出才对。
业精于勤,荒于嬉;行成于思,毁于随。
我的理解:首先,process.nextTick 的优先级比 setImmediate 高。其次,总是先按照优先级执行已存在的定时器方法,然后按照优先级执行异步回调中的定时器方法。最后,异步回调藏的越深,优先级就要降一层。
测试代码:
process.nextTick(function(){ console.log('1'); }); process.nextTick(function(){ console.log('2'); }); setImmediate(function(){ console.log('3'); setImmediate(function() { console.log('4'); process.nextTick(function(){ console.log('5'); process.nextTick(function(){ console.log('6'); }); }); }); process.nextTick(function(){ console.log('7'); }); }); process.nextTick(function(){ console.log('8'); }); setImmediate(function(){ console.log('9'); process.nextTick(function(){ console.log('10'); }); }); console.log('0');
验证输出:
0 1 2 8 3 9 7 10 4 5 6
https://github.com/JacksonTia...
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
我的理解:
首先,process.nextTick 的优先级比 setImmediate 高。
其次,总是先按照优先级执行已存在的定时器方法,然后按照优先级执行异步回调中的定时器方法。
最后,异步回调藏的越深,优先级就要降一层。
测试代码:
验证输出:
https://github.com/JacksonTia...