防抖节流

141 阅读1分钟

防抖

  • 如果timer存在,清除定时器重新计算时间,如果timer不存在,开始计算时间执行fn
function debounce(fn, delay) {
    let timer = null;
    return function () {
        const _this = this;
        if (timer) {
            clearTimeout(timer)
            timer = null;
        }
        timer = setTimeout(() => {
            fn.apply(_this, arguments);
            clearTimeout(timer)
            timer = null;
        }, delay);
    }
}


function fn(e) {
    console.log(this)
    console.log(e.target.id)
}
document.getElementById('app').onscroll = debounce(fn, 1000)

节流

  • 如果flag为true,则可以去执行fn,如果flag为false,则不执行fn
function throttle(fn, delay) {
    let flag = true;
    return function () {
        const _this = this;
        if (flag) {
            flag = false;
            setTimeout(() => {
                fn.apply(_this, arguments);
                flag = true;
            }, delay);
        }
    }
}

function fn(e) {
    console.log(this)
    console.log(e.target.id)
}
document.getElementById('app').onscroll = throttle(fn, 1000)