{{msg}}
事件循坏vent loop中,每一次循环称为tick,每一次tick的任务如下:
执行栈选择最先进入队列的宏任务(一般都是script),执行其同步代码直至结束;
检查是否存在微任务,有则会执行至微任务队列为空;
如有必要会渲染页面;
开始下一轮tick,执行宏任务中的异步代码(settimeout的回调等)。
宏任务与微任务
宏任务(macrotask)
宿主(node、浏览器)发起的任务;
在es6规范中,将其称为task;
script、settimeout、setinterval、i/o、ui rendering、postmessage、messagechannel、setimmediate
微任务(microtask)
js引擎发起的任务;
在es6规范中,将其称为jobs;
promise、mutaionobserver、process.nexttick
var app = new vue({
el: '#app',
data: {
msg: '点击按钮判断控制台打印的内容'
},
methods: {
clickme() {
this.msg = '执行顺序 同步 => promise => settimeout'
console.log('start')
settimeout(() => {
console.log('timeout')
}, 0)
this.$nexttick(() => {
console.log('nexttick')
this.$nexttick(() => {console.log('nexttick2')})
settimeout(() => {
console.log('timeout2')
}, 0)
})
console.log('end')
}
// 先执行同步在执行异步 => 执行$nexttick返回promise,执行timeout (promise比timeout快)
// 事件循环机制: 同步 => 微任务 => 渲染页面 => 开始下一轮,执行宏任务中的异步代码(settimeout的回调等)
// 为什么promise比timeout快 https://blog.csdn.net/weixin_34365635/article/details/91421326
// 1. start
// 2. end
// 3. nexttick
// 4. nexttick2
// 5.nexttick2
// 6.timeout
// 7.timeout2
}
})