防抖、节流函数

23 阅读1分钟

防抖函数

function debounce (fn, duration) {
    let timerId;
    return function (...args) {
        clearTimeout(timerId);
        timerId = setTimeout(() => {
            // fn.apply(this, Array.prototype.slice.apply(arguments));
            fn.apply(this, args);
        }, duration);
    }
}

节流函数

function throttle (fn, duration) {
    let timerId;
    return function (...args) {
        if (!timerId) {
            timerId = setTimeout(() => {
                // fn.apply(this, Array.prototype.slice.apply(arguments));
                fn.apply(this, args);
                timerId = null
            }, duration);
        }
    }
}