在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 關(guān)于js事件循環(huán)一些疑問(wèn)

關(guān)于js事件循環(huán)一些疑問(wèn)

有一些關(guān)于javascript的事件循環(huán)機(jī)制的疑問(wèn),js是單線(xiàn)程語(yǔ)言,執(zhí)行過(guò)程中,遇到異步任務(wù)會(huì)將異步任務(wù)單獨(dú)放在一個(gè)任務(wù)隊(duì)列中,等到主線(xiàn)程中的任務(wù)執(zhí)行完成后,再由事件循環(huán)機(jī)制將已經(jīng)完成的異步任務(wù)放入主線(xiàn)程中執(zhí)行。
給頁(yè)面的DOM元素綁定的事件(比如click事件),也是異步的,需要觸發(fā)之后才會(huì)執(zhí)行相應(yīng)的代碼,那么此類(lèi)DOM事件和異步事件(比如setTimeOut、ajax等)的本質(zhì)區(qū)別是什么呢?DOM事件的觸發(fā)是否也是通過(guò)事件循環(huán)機(jī)制來(lái)控制的?

回答
編輯回答
念初

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

同步

比如如鼠標(biāo)事件

我們都知道macrotask執(zhí)行完后,需要檢查有沒(méi)有microtask,如果有則執(zhí)行microtask,之后才會(huì)執(zhí)行macrotask。那么我只要知道promise回調(diào)在什么時(shí)候執(zhí)行,就知道這是個(gè)異步的還是同步的。

舉個(gè)栗子
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

2017年4月18日 17:18
編輯回答
維她命

DOM事件本質(zhì)上是EventEmitter(發(fā)布訂閱模式),需要注冊(cè)事件,然后需要滿(mǎn)足條件才可以觸發(fā)事件,一個(gè)div上本身并沒(méi)有click事件,因?yàn)槟阍谒厦孀?cè)了click事件,它才會(huì)在你點(diǎn)擊的時(shí)候觸發(fā)。
setTimeOut、ajax是瀏覽器自帶的api,你可以直接拿來(lái)用。

2017年12月22日 10:50
編輯回答
初念

你說(shuō)的這個(gè)click準(zhǔn)確來(lái)講是設(shè)計(jì)模式中的訂閱發(fā)布者模式

使用訂閱發(fā)布者模式編寫(xiě)異步場(chǎng)景的代碼更加合理清晰

2017年7月12日 14:52