Comments (7)
- 事件循环机制就是基于
事件触发线程
的
from blog.
异步执行线程
- JS引擎线程
- 事件触发线程
- 定时触发器线程
from blog.
异步执行
- JS分为同步任务和异步任务
- 同步任务都在主线程上执行,形成一个
执行栈
- 主线程之外,事件触发线程管理着一个
任务队列
,只要异步任务有了运行结果,就在任务队列之中放置一个事件。 - 一旦执行栈中的所有同步任务执行完毕(此时JS引擎空闲),系统就会读取任务队列,将可运行的异步任务添加到
可执行栈中,开始执行
from blog.
from blog.
- 主线程运行时会产生
执行栈
, - 栈中的代码调用某些api时,它们会在事件队列中添加各种事件(当满足触发条件后,如ajax请求完毕->异步线程执行)
- ?比如在队列里创建一个ajax请求事件,ajax请求由http异步线程执行,等请求完成返回结果,在队列里添加一个事件
- 而栈中的代码执行完毕,就会读取事件队列中的事件,去执行那些回调
如此循环 - 注意,总是要等待栈中的代码执行完毕后才会去读取事件队列中的事件
from blog.
定时器
- 当使用
setTimeout
或setInterval
时,它需要定时器线程计时,计时完成后就会将特定的事件推入事件队列中
from blog.
使用MutationObserver实现microtask
- MutationObserver可以用来实现microtask(它属于microtask,优先级小于Promise,
一般是Promise不支持时才会这样做) - 它是HTML5中的新特性,作用是:监听一个DOM变动,当DOM对象树发生任何变动时,
Mutation Observer
会得到通知 - 像以前的Vue源码中就是利用它来模拟nextTick的,具体原理是,创建一个TextNode并监听内容变化,
然后要nextTick的时候去改一下这个节点的文本内容,
如下:(Vue的源码,未修改)
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
不过,现在的Vue(2.5+)的nextTick实现移除了MutationObserver的方式(据说是兼容性原因),
取而代之的是使用MessageChannel
(当然,默认情况仍然是Promise,不支持才兼容的)。
MessageChannel属于宏任务,优先级是:setImmediate->MessageChannel->setTimeout,
所以Vue(2.5+)内部的nextTick与2.4及之前的实现是不一样的,需要注意下。
from blog.
Related Issues (20)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.