Skip to content

防抖

js
// debounce
// 原则是调用的最后一次,延迟之后再执行。

const debounce = (fn, delay=300) => {
    let timer = null;
    return function(...args){ // 这里不能改成箭头函数
        if(timer) clearTimeout(timer);
        timer = setTimeout(()=>{fn.apply(this,args)}, delay)
    }
}

节流

js
const throttle = (fn, ...args) => {
    let inThrottle = false;

    return function(...args){

        if(inThrottle){
            return;
        }

        fn.apply(this, args);

        inThrottle = true;

        setTimeout(()=>{
            inThrottle = false;
        },delay);
    }
}
本站访客数 人次 本站总访问量