函数的防抖 - JavaScript实现
函数的防抖(debounce)
一. 定义
规定一个时间段,在该时间段内若再次调用该函数则重新计时,否则执行该函数。
二. 实现
- 在时间段结束时执行函数
function debounceEnd(fn, wait) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, wati)
};
}
- 在时间段的开始时执行函数
function debounceStart(fn, wait) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (!timer) {
fn.apply(context, args);
} else {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
}, wait);
};
}
- 两者结合
function debounce(fn, wait, immediate = false) {
let timer = null;
return function() {
const context = this;
const args = arguments;
if (immediate) {
if (!timer) {
fn.apply(context, args);
} else {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
}, wait);
} else {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, wait);
}
};
}
三. 函数防抖的作用
前端开发过程中,有一些事件,常见的例如,onresize,scroll,mousemove 等,会被频繁触发(短时间内多次触发),如果不做限制的话,会造成浪费计算机资源,还会降低程序运行速度,甚至造成浏览器卡死、崩溃。函数的节流防抖可以减少这些不必要的频繁操作,提升性能,带来更好的用户体验。