[Javascript] Microtasks exec order

button.addEventListener(
    'click',
    (event) => {
        console.log('listener 1')
        queueMicrotask(() => {
            console.log('microtask')
        })
    }
)

button.addEventListener(
    'click',
    (event) => {
        console.log('listener 2')
    }
)

The order should be

listener 1
microtask
listener 2

 

For first click event task:

  • after finish console.log('listener 1'), callstack is empty
  • then because of callstack is empty, microtask will be executed
  • Then second click event will be added to callstack

 

But things got changed for dispatchEvent

button.addEventListener(
    'click',
    (event) => {
        console.log('listener 1')
        queueMicrotask(() => {
            console.log('microtask')
        })
    }
)

button.addEventListener(
    'click',
    (event) => {
        console.log('listener 2')
    }
)

button.dispatchEvent(new MouseEvent('click'))

Order:

listener 1
listener 2
microtask
  • dispatchEvent will stay, so the callstack is not empty
  • therefore first run listener 1
  • then listener 2
  • then microtask

posted @   Zhentiw  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-06-02 Fixing error: “chromedriver” cannot be opened because the developer cannot be verified. Unable to launch the chrome browser on Mac OS
2021-06-02 [AWS - DA] AWS Integration & Messaging: SQS, SNS
2021-06-02 [AWS DA] AWS Monitoring & Audit: CloudWatch, X-Ray and CloudTrail
2021-06-02 [AWS DA] Database types & SSL
2020-06-02 [Functional Programming] Alternative operator for Either
2020-06-02 [React] Use Environment Variables with Create React App
2019-06-02 [ML] The Basics: Training Your First Model
点击右上角即可分享
微信分享提示