Skip to content

函数防抖

一些场景:

  • input输入框input事件,频繁触发耗时操作
  • 窗口resize事件,频繁触发耗时操作
  • window的mousemove事件

防抖函数最佳实践特点:

  1. 频繁触发,耗时操作
  2. 只有最后一次的操作触发才有意义

接下来书写一个防抖函数,需要解决:

  1. 延时触发耗时操作,中间不论多少次触发都不执行,只执行最后一次的有意义的触发操作。
  2. 更改this指向问题
  3. 将事件参数原封不动的传递出去
js
/**
 * fn 回调函数
 * duration 延时时间
 */
function debounce(fn,duration){
    let timerId=null;
    return function(){
        clearTimeout(timerId);

        //返回函数-此处环境this指向是input元素
        const currThis=this;
        //arguments:伪数组-可以获取到函数的参数
        const args=Arrar.prototype.slice.call(arguments,0);
        
        setTimeout(()=>{
            fn.apply(currThis,args);//更改回调函数fn的this指向
        },duration)
    }
}

使用方法:

js
input.oninput=debounce(()=>{
    console.log('触发输入框input事件',this.value);
},500)

window.onmousemove=debounce(()=>{
    console.log('window-触发鼠标移动事件');
},500)

this的指向取决于函数如何调用的

MIT License