关于js事件循环一些疑问

有一些关于javascript的事件循环机制的疑问,js是单线程语言,执行过程中,遇到异步任务会将异步任务单独放在一个任务队列中,等到主线程中的任务执行完成后,再由事件循环机制将已经完成的异步任务放入主线程中执行。
给页面的DOM元素绑定的事件(比如click事件),也是异步的,需要触发之后才会执行相应的代码,那么此类DOM事件和异步事件(比如setTimeOut、ajax等)的本质区别是什么呢?DOM事件的触发是否也是通过事件循环机制来控制的?

回复
阅读 1.3k
3 个回答

你说的这个click准确来讲是设计模式中的订阅发布者模式

使用订阅发布者模式编写异步场景的代码更加合理清晰

DOM事件本质上是EventEmitter(发布订阅模式),需要注册事件,然后需要满足条件才可以触发事件,一个div上本身并没有click事件,因为你在它上面注册了click事件,它才会在你点击的时候触发。
setTimeOut、ajax是浏览器自带的api,你可以直接拿来用。

DOM事件既有同步有也异步。

同步

比如如鼠标事件

我们都知道macrotask执行完后,需要检查有没有microtask,如果有则执行microtask,之后才会执行macrotask。那么我只要知道promise回调在什么时候执行,就知道这是个异步的还是同步的。

举个栗子
http://jsfiddle.net/631807682...

异步

比如load事件

W3文档

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.

DOM-Level-3-Events

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏