Loading

「跟着渡一学前端」手写防抖函数

完成代码

function debounce(fn,delay){
  let timerId;
  return function(...args){
    clearTimeout(timerId);
    timerId=setTimeout(()=>{
      fn.apply(this,args);
    },delay);
  };
}

//使用
const d_fun=debounce(fun,500);

知识细节

使用条件

  1. 高频(极短时间内高频触发)
  2. 耗时
    • CPU密集——> 计算复杂场景
    • IO密集——>读写文件
  3. 以最后以一次调用为准

代码深究

Q:为什么不使用箭头函数?

A:目的:方便将 使用时目标对象 的this透传至 防抖函数返回对象 中的this。

​ 但是箭头函数没有this,只有写成一个普通函数后,才有this

posted @ 2025-02-15 09:57  lao-jiawei  阅读(12)  评论(0)    收藏  举报