节流、防抖

js 防抖和节流

在进行窗口的resize、scroll,输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负担,导致用户体验非常糟糕。此时我们可以采用debounce(防抖)和throttle(节流)的方式来减少调用频率,同时又不影响实际效果。

函数防抖

函数防抖(debounce):当持续触发事件时,一定时间内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了时事件,就重新开始延时。

1
2
3
4
5
6
7
8
9
10
11
function debounce(fn, delay) {
let timer = null;

return function() {
if (timer) {
clearTimeout(timer);
}

timer = setTimeout(fn, delay);
}
}

函数节流

函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

节流 throttle(时间缀版)

1
2
3
4
5
6
7
8
9
10
11
12
function throttle(fn, delay) {
let prev = Date.now();

return function() {
let now = Date.now();

if (now - prev >= delay) {
fn.apply(this, arguments);
prev = Date.now();
}
}
}

节流 throttle(定时器版)

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

节流 throttle (时间缀+定时器版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function throttle(fn, delay) {
let timer = null;
let startTime = Date.now();

return function() {
let _that = this;
let args = arguments;

let nowTime = Date.now();

clearTimeout(timer);

if (nowTime - startTime >= delay) {
fn.apply(_that, args);
startTime = Date.now();
} else {
timer = setTimeout(fn, delay - (nowTime - startTime));
}
}
}

总结

函数防抖:将几次操作合并为一次操作进行。原理是维护一个计时器,规定在 delay 时间后触发函数,但是在 delay 时间内再次触发的话,就会取消之前的计时器而重新设置。这样一来,只有最后一次操作能被触发。

函数节流:函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 AJAX 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。