前端防抖与节流

前端防抖与节流

前端防抖与节流的实现

前言

防抖与节流的应用场景,以及如何选择,以及如何实现,以及如何优化,以及如何测试,以及如何调试。所谓防抖是指:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。所谓节流是指:规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。所谓节流是指:规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。

防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function debounce(fn, wait) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
fn.apply(context, args);
}, wait);
}
}

节流

1
2
3
4
5
6
7
8
9
10
11
12
13
function throttle(fn, wait) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args);
timer = null;
}, wait);
}
}
}

前端防抖与节流
https://wenzhaoabc.github.io/front/debounce-stream-js/
作者
wenzhaoabc
发布于
2023年10月21日
许可协议