美文网首页
浅谈debounce & throttle 极简思想

浅谈debounce & throttle 极简思想

作者: 小仙有毒_1991 | 来源:发表于2020-08-13 08:37 被阅读0次

原因:
通常绑定响应鼠标移动、窗口大小调整、滚屏等事件时,绑定的函数触发的频率会很频繁。
若稍处理函数微复杂,需要较多的运算执行时间和资源,往往会出现延迟,甚至导致假死或者卡顿感。
目的:
为了优化性能,这时就很有必要使用debouncethrottle

debounce函数通常称为防抖动函数,该函数会从上一次被调用后,延迟 wait 毫秒后调用 fn.

//简单实现
function debounce(fn, wait) {   
    wait = wait || 0;   
    let timer;    
 
    return function () {   
        if (timer) {   
            clearTimeout(timer);
            timer= null;   
        }  
        timer= setTimeout(function() {   
            fn();
      }, wait);
   };
 }

throttle节流函数,在 wait 秒内最多执行 fn 一次的函数。

function throttle( fn ,delay){
delay = delay || 0;
var timer, lastTime = 0;
return function(){
var current = new Date().getTime();
if(current >= lastTime + delay){
fn();
lastTime = current;
}else{
if (timer ) {
clearTimeout(timer );
timer = null;
}
timer = setTimeout(function(){
fn();
},delay)
}
}
}

相关文章

网友评论

      本文标题:浅谈debounce & throttle 极简思想

      本文链接:https://www.haomeiwen.com/subject/nghpdktx.html