节流与防抖

94 阅读1分钟

节流和防抖都是常用技巧,本文使用window滚动作为事件,触发节流和防抖

节流

// 利用setTimeout
function throttle(fn, interval = 300) {
    let canRun = true;
    return function () {
        if (!canRun) return;
        canRun = false;
        setTimeout(() => {
            fn.apply(this, arguments);
            canRun = true;
        }, interval)
    }
}

// 利用时间戳
function throttle(fn, interval = 300) {
    var previous = 0;
    return function() {
        let now = new Date();
        // if (now - previous > interval) {
        //     previous = now;
        //     fn.apply(this, arguments);
        // }
        if (now - previous < interval) {
            return;
        }
        previous = now;
        fn.apply(this, arguments);
    }
}

// 构建新方法
var closureFun = throttle(function() {
    let pageHeight = document.body.scrollHeight,
    scrollTop = window.scrollY,
    winHeight = window.innerHeight,
    thresold = pageHeight - scrollTop - winHeight;
    console.log(thresold);
    if (thresold > -100 && thresold <= 20) {
        console.log('end');
    }
}, 1000)

// 复制进入 chrome dev tool 完成demo
var closureFun = throttle(function() {
    let pageHeight = document.body.scrollHeight,
    scrollTop = window.scrollY,
    winHeight = window.innerHeight,
    thresold = pageHeight - scrollTop - winHeight;
    console.log(thresold);
    if (thresold > -100 && thresold <= 20) {
        console.log('end');
    }
}, 1000)
// 绑定事件
window.addEventListener('scroll', closureFun);

防抖

function debounce(fn, interval = 300) {
    let timeout = null;
    return function () {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this, arguments)
        }, interval)
    }
}

function debounce(fn, interval = 300) {
    let timeout = null;
    return function () {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this, arguments)
        }, interval)
    }
}

// 复制进入 chrome dev tool 完成demo
var debounceFun = debounce(function() {
    let pageHeight = document.body.scrollHeight,
    scrollTop = window.scrollY,
    winHeight = window.innerHeight,
    thresold = pageHeight - scrollTop - winHeight;
    console.log(thresold);
    if (thresold > -100 && thresold <= 20) {
        console.log('end');
    }
}, 1000)
// 绑定事件
window.addEventListener('scroll', debounceFun);