函数节流和防抖函数

《节流函数》

  • 一个函数执行一次后,只有大于设定的时间才会执行第二次
  • 有个需要频繁触发的函数,出于性能角度,在规定时间内,只让函数触发的第一次生效,后面不生效
  • 实现代码 
    function throttle(callback, wait) {
        wait = wait || 300;//默认节流300毫秒触发
        var lastTime = 0;//记录上一次函数触发的时间
        return function () {
            var nowTime = Date.now();
            if (lastTime < 1 || nowTime - lastTime >= wait) {
                callback.apply(this, arguments);
                lastTime = nowTime;
            }
        }
    }

《防抖函数》

  • 一个需要频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效
  • 实现代码
    function debounce(callback, wait){
        wait = wait || 300;//默认防抖300毫秒触发
        var timer = null;
        return function(){
            //清除上一次的延时器
            clearTimeout(timer);
            //重新设置新的延时器
            timer = setTimeout(function(args) {
                callback.apply(this, args);
            }.bind(this, arguments), wait);
        }
    }

     

 

posted @ 2020-11-08 17:28  智走  阅读(100)  评论(0)    收藏  举报