JavaScript运行机制 & 节流防抖

JS运行机制

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
console.log('script start');
setTimeout(function(){
console.log('settimeout');

},0)
new Promise(resolve=>{
console.log('promise1');
resolve()
}).then(function(){
console.log('promise2');

}).then(function(){
console.log('promise3');

})
console.log('script end');

// 执行环境 执行环境会被顺序的加入到执行栈中 如果遇到异步的代码 会被挂起并且加入到Task队列当中
// 一旦执行栈为空 Event loop 就会从task队列当中 拿出需要执行的代码并放入到执行栈中执行
// js的异步行为也是同步行为
// 不同的任务源 会被分配到不同的Task队列当中 任务源可以分为 微任务(microtask) 宏任务 (macrotask)
// 微任务 promise
// 宏任务 setTimeout script
// 1 执行同步代码 属于宏任务 2 执行栈为空 需要查询是否有微任务需要执行 3 执行所有的微任务 4 必要的话渲染ui 5 执行宏任务中的异步代码

// 宏任当中 大量的需要操作dom 为了更快的页面响应 可以把操作dom放到微任务中

防抖和节流

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
// 防抖
// 当我们连续触发事件的时候 一定时间段没有触发事件 事件处理函数才会执行一次
// 如果设定的时间内又触发了事件 会重新开始计时 计时的点是在你最后一次点击开始
function deb(fn,wait){
var timeout = null
return function(){
if(timeout !== null)
clearTimeout(timeout)

timeout = setTimeout(fn,wait)

}
}
function handel(){
// 发送ajax请求
console.log(Math.random());

}
document.getElementById('btn').onclick= deb(handel,1000)

// 触发事件保证一段时间内只调用一次 休息时间5秒 5秒内就是休息 一旦过了5秒开始营业
// 滚动条
function handeler(){
console.log(Math.random());

}
function thr(fn,delay){
let flag = true;
return function(){
if(!flag){
// 休息
return false
}
// 营业
flag = false
fn()
setTimeout(()=>{
flag = true
},delay)
}
}
document.getElementById('btn').onclick= thr(handeler,3000)