# JS执行机制
参考文章 Tasks, microtasks, queues and schedules (opens new window)
# 术语
- Tasks 任务队列
- Microtasks 微任务队列
- JS stack JS执行栈
- MutationObserver
- 队列(先进先出) 排队买饭
- 栈(先进后出)羽毛球桶里放进去羽毛球,然后再把羽毛球拿出来
# 代码
<style>
.outer{
width: 500px;
height: 500px;
background: red;
}
.inner{
width: 200px;
height: 200px;
background: blue;
}
</style>
<div class="outer">
<div class="inner"></div>
</div>
<script>
// Let's get hold of those elements
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
// Let's listen for attribute changes on the
// outer element
new MutationObserver(function () {
console.log('mutate');
}).observe(outer, {
attributes: true,
});
// Here's a click listener…
function onClick() {
console.log('click');
setTimeout(function () {
console.log('timeout');
}, 0);
Promise.resolve().then(function () {
let i = 0
let num = 0
while(i < 1000000000) {
num += i
i++
}
console.log('num', num)
console.log('promise');
});
outer.setAttribute('data-random', Math.random());
}
// …which we'll attach to both elements
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
// 注意
// 注意
// 注意
自动触发 onclick事件和 手动点击inner触发事件执行顺序不同
inner.onclick()
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63