Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

点击鼠标和主动调用click方法有什么不同,为什么有下面这种现象。

<button id="btn">click</button>
<script>
 var oBtn = document.getElementById('btn')
    oBtn.addEventListener('click', function () {
        Promise.resolve().then(() => console.log('微任务 1'))
        console.log('listener1')
    })
    oBtn.addEventListener('click', function () {
        Promise.resolve().then(() => console.log('微任务 2'))
        console.log('listener2')
    })
    oBtn.click()
</script>

调用click方法的打印结果
listener1
listener2
微任务 1
微任务 2

点击按钮的打印结果
listener1
微任务 1
listener2
微任务 2

为什么会产生这种差异


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. 通过JS(dispatchEvent, HTMLElement.click, HTMLElement.focus等)派发的事件的事件处理函数都是同步调用的;
  2. 用户触发的事件的事件处理函数都是异步调用的。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...