有一些关于javascript的事件循环机制的疑问,js是单线程语言,执行过程中,遇到异步任务会将异步任务单独放在一个任务队列中,等到主线程中的任务执行完成后,再由事件循环机制将已经完成的异步任务放入主线程中执行。
给页面的DOM元素绑定的事件(比如click事件),也是异步的,需要触发之后才会执行相应的代码,那么此类DOM事件和异步事件(比如setTimeOut、ajax等)的本质区别是什么呢?DOM事件的触发是否也是通过事件循环机制来控制的?
有一些关于javascript的事件循环机制的疑问,js是单线程语言,执行过程中,遇到异步任务会将异步任务单独放在一个任务队列中,等到主线程中的任务执行完成后,再由事件循环机制将已经完成的异步任务放入主线程中执行。
给页面的DOM元素绑定的事件(比如click事件),也是异步的,需要触发之后才会执行相应的代码,那么此类DOM事件和异步事件(比如setTimeOut、ajax等)的本质区别是什么呢?DOM事件的触发是否也是通过事件循环机制来控制的?
DOM事件本质上是EventEmitter(发布订阅模式),需要注册事件,然后需要满足条件才可以触发事件,一个div上本身并没有click事件,因为你在它上面注册了click事件,它才会在你点击的时候触发。
setTimeOut、ajax是浏览器自带的api,你可以直接拿来用。
DOM事件
既有同步有也异步。
比如如鼠标事件
我们都知道macrotask
执行完后,需要检查有没有microtask
,如果有则执行microtask
,之后才会执行macrotask
。那么我只要知道promise
回调在什么时候执行,就知道这是个异步的还是同步的。
举个栗子
http://jsfiddle.net/631807682...
比如load
事件
Events may be dispatched either synchronously or asynchronously.Events which are synchronous (sync events) are treated as if they are in a virtual queue in a first-in-first-out model, ordered by sequence of temporal occurrence with respect to other events, to changes in the DOM, and to user interaction. Each event in this virtual queue is delayed until the previous event has completed its propagation behavior, or been canceled. Some sync events are driven by a specific device or process, such as mouse button events. These events are governed by the event order algorithms defined for that set of events, and user agents will dispatch these events in the defined order.
Events which are asynchronous (async events) may be dispatched as the results of the action are completed, with no relation to other events, to other changes in the DOM, nor to user interaction.
4 回答5.2k 阅读✓ 已解决
11 回答4.1k 阅读
7 回答2.8k 阅读✓ 已解决
11 回答2.6k 阅读
5 回答1.6k 阅读✓ 已解决
8 回答2k 阅读✓ 已解决
6 回答1.2k 阅读
你说的这个click准确来讲是设计模式中的订阅发布者模式
使用订阅发布者模式编写异步场景的代码更加合理清晰