# 手写节流 防抖
# 节流
n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效 (类似于技能冷却)
const throttle = (fn, time) => {
let timer = null
return (...args) => {
if(timer) {return}
fn.call(undefined, ...args)
timer = setTimeout(()=>{
timer = null
}, time)
}
}
const test = throttle(()=>{console.log('hi')}, 3000)
test() // hi
test()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
间隔一段时间就执行一次回调的应用场景:搜索框的联想功能
# 防抖
n 秒后再执行该事件,若在 n 秒内被重复触发,则重新计时 (类似于点击回城)
const debounce = (fn, time) => {
let timeout = null
return (...args) => {
if (timeout !== null) {
clearTimeout(timeout) // 清除上一个定时器 重新计时 注意timeout这里不是null
}
timeout = setTimeout(()=>{
fn.call(undefined, ...args)
timeout = null
}, time)
}
}
const test1 = debounce(()=>{console.log('ing')}, 3000)
test1() // 过3秒打印出ing
test1()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
只需触发一次回调的应用场景:输入框验证,窗口调整大小,搜索框搜索(输入完再发送请求)