xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript microtask Guide All In One

JavaScript microtask Guide All In One

JavaScript 微任务指南 All In One

task queue / 任务队列

microtask queue / 微任务队列

//

queueMicrotask


let id = setInterval(() => {
  console.log(`5`);
  clearInterval(id);
});

setTimeout(() => {
  console.log(`4`);
});

Promise.resolve().then(() => console.log(`2`));

queueMicrotask(() => {
  console.log(`3`);
});

console.log(`1`);

/*

1
2

3
4
5

*/

why is the setInterval task executed slower than the setTimeout task in the browser javascript environment?

为什么在浏览器 javascript 环境下 setInterval 任务执行速度比 setTimeout 任务慢?

setTimeout(() => {
  console.log(`4`);
});

let id = setInterval(() => {
  console.log(`5`);
  clearInterval(id);
});

Promise.resolve().then(() => console.log(`2`));

queueMicrotask(() => {
  console.log(`3`);
});

console.log(`1`);

/*

1
2

3
4
5

*/

image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide

microtask in depth

https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth

Deep Dive into the JavaScript Event Loop All In One

事件循环的本质:
js 触发的所有事件都会被转化成一个任务,依次放到任务队列中排队,等待被主线程执行(单线程机制);
从宏任务队列中,队头取出一个任务,先依次执行该任务中的所有同步代码,然后在依次执行所有异步代码
异步代码中,先执行完微任务队列中的微任务,在执行其他的宏任务
当该任务执行完毕,接着检查任务队列是否为空,不为空就接着执行下一个宏任务;
就这样不断的重复执行以上步骤,进行事件循环的持续;

https://www.cnblogs.com/xgqfrms/p/17162275.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-03-01 23:14  xgqfrms  阅读(32)  评论(2编辑  收藏  举报