You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functiondebounce(fn){lettimer=null;returnfunction(){clearTimeout(timer);timer=setTimeout(()=>{// this 指向 input,fn.apply(this,arguments);// 不修改 this 指向的话,doRequest 中, this 指向 window// fn()},500);};}functiondoRequest(){console.log(this.value);console.log(arguments);}document.getElementById("app").innerHTML="防抖输入框 <input id='input' />";document.getElementById("input").addEventListener("input",debounce(doRequest));
1.防抖
思路:再次触发的时候,取消上次的定时器。
不改变 this 指向,效果如下:
2.节流
思路:n 秒内执行的时候,判断是否有定时器,如果有,则跳过此次执行。
换种写法:
运行结果:
扩展
问:throttle 或 debounce 中 return 的函数能用箭头函数吗?
答:不能,如果使用箭头函数,return 函数中this指向 window ;不使用箭头函数,this 指向 input。
The text was updated successfully, but these errors were encountered: