防抖节流
防抖(debounce)
所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
节流(throttle)
**所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。**节流会稀释函数的执行频率。
对于节流,一般有两种方式可以实现,分别是时间戳版和定时器版。
防抖:
let time2;
document.getElementById('防抖').onclick =
function () {
clearTimeout(time2);
time2=setTimeout(function () {
//做一些快乐的事情
},2000);
};
节流:
let bool=true;
document.getElementById('节流').onclick = function () {
if(bool){
//做一些开心的事情
bool=false;
setTimeout(()=>{
bool=true
},2000)
}
}
作者:郑掌声
链接:https://juejin.im/post/5da7c77a51882554c0757f46
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
修改页面 (opens new window)
Last Updated: 12/20/2021, 5:53:52 AM