节流

节流

一、什么是节流?

节流是在一段时间间隔t中,多次触发相同的事件,事件只执行一次,并且执行的事件和下一次事件时间相隔t

二、场景

2.1 鼠标移动,使用节流限制移动时间的触发频率,避免过多的计算个页面渲染

2.2 滚动事件,用户触发滚动scroll事件,可以使用节流来减少执行次数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let fater = document.querySelector(".father")
let timer = null
fater.addEventListener("scroll", () => {
if (timer) {
return
}
timer = setTimeout(() => {
console.log("节流")
timer = null
}, 1000)
})

if (null) {
console.log(111)
} else {
console.log(222)
}

三、封装

1
2
3
4
5
6
7
8
9
function debounce(fn, timeout) {
let timer = null
return function () {
if (timer) return
timer = setTimeout(() => {
fn()
}, timeout)
}
}

本文作者:finyou

本文链接:http://finyou.top/2026/04/03/optimize/throttle/

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

ESC 关闭 | 导航 | Enter 打开
输入关键词开始搜索