防抖和截流

82 阅读1分钟

防抖

事件连续触发,只执行最后一次回调函数,如文本框输入搜索。

function debounce(fn, delay) {
    var timer = null;
    return function() {
        if(timer) 
        clearTimeout(timer);
        timer = setTimeout(fn, delay);
    }
}

function handle() {
    console.log(Math.random()); 
}

window.addEventListener('scroll', debounce(handle, 1000));

节流(throttle)

事件触发,函数执行,一定时间内函数无法再次执行,如resize、scroll、mousemove等事件触发监听。

function throttle(fn,delay){  
    let valid = true;  
    return function() { 
        if(!valid){      
            return false;
        }    
        valid = false;    
        setTimeout(() => {
           fn();
           valid = true;
        }, delay)   
    }
}