「跟着渡一学前端」手写防抖函数
完成代码
function debounce(fn,delay){
let timerId;
return function(...args){
clearTimeout(timerId);
timerId=setTimeout(()=>{
fn.apply(this,args);
},delay);
};
}
//使用
const d_fun=debounce(fun,500);
知识细节
使用条件
- 高频(极短时间内高频触发)
- 耗时
- CPU密集——> 计算复杂场景
- IO密集——>读写文件
- 以最后以一次调用为准
代码深究
Q:为什么不使用箭头函数?
A:目的:方便将 使用时目标对象 的this透传至 防抖函数返回对象 中的this。
但是箭头函数没有this,只有写成一个普通函数后,才有this

浙公网安备 33010602011771号