节流和防抖

作用:减少调用频率,减轻浏览器负担,提高用户体验

场景:

  函数防抖(debounce):当持续触发事件时,在一定时间(wait)内没有再次触发,则执行处理函数。若在期间有触发了事件,那么重当前时间开始重新计时。(搜索框)

  节流(throttle):一定时间段内只能触发一次处理函数

函数防抖实现:

function debounce(fn, wait) {
    var timeout = null;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(fn, wait);
    }
}
// 处理函数
function handle() {
    console.log(Math.random()); 
}
// 滚动事件
window.addEventListener('scroll', debounce(handle, 1000));

 

函数节流实现:

 
定时器实现--第一次先等待再 执行
var throttle = function(func, delay) {
            var timer = null;
            return function() {
                var context = this;
                var args = arguments;
                if (!timer) {
                    timer = setTimeout(function() {
                        func.apply(context, args);
                        timer = null;
                    }, delay);
                }
            }
        }
        function handle() {
            console.log(Math.random());
        }
        window.addEventListener('scroll', throttle(handle, 1000));
     2.时间戳实现---第一次先执行    
        function throttle(func,wait){
            var lastTime = 0;
            return function(){
                var nowTime = +new Date();
                if(nowTime -lastTime >wait){
                    func.apply(this,arguments);
                    lastTime = nowTime;
                }
            }
        } 
posted @ 2020-01-05 22:39  StupidTom  阅读(128)  评论(0编辑  收藏  举报