节流及防抖

431 阅读1分钟

防抖

防抖:在连续触发某个函数时,我们只在最后的时候,让对应的函数执行;

function debounce(fn,wait){
    wait = wait || 100;
    var timer = null;
    return function(){
        clearTimeout(timer);
        timer = setTimeout(()=>{
            fn.apply(this,arguments);//保证this的指向 和 参数的传递
        },wait)
    }
}
let fn = function(){console.log(this)}
let f = debounce(fn)
window.onscroll = f;

节流

节流:在连续触发某个函数时,我们每隔一段时间就触发一次该函数

function throttle(fn,wait){
    wait = wait || 1000;
    var flag = true;
    return function(){
        if(!flag) return;
        flag = false;
        setTimeout(()=>{
            flag = true;
            fn.call(this,...arguments)
        },wait)
    }
}
function f(){console.log(this)}
window.onscroll = throttle(f)