函数的防抖与节流

124 阅读1分钟

函数的防抖与节流,仅供参考

    /* 清除定时器 函数的节流和防抖使用 */
    const clearTimer = function clearTimer(timer) {
        if (timer) {
            clearTimeout(timer);
        }
        return null;
    };

    /* 函数的防抖 */
    const debounce = function debounce(func, wait, immediate) {
        if (typeof func !== 'function')
            throw new TypeError(`${func} must be an function`);
        if (typeof wait === 'boolean') immediate = wait;
        if (typeof wait !== 'number') wait = 500;
        if (typeof immediate !== 'boolean') immediate = false;
        let timer = null;
        return function operate(...params) {
            let now = !timer && immediate,
                result;
            timer = clearTimer(timer);
            timer = setTimeout(() => {
                timer = clearTimer(timer);
                if (!immediate) func.call(this, ...params);
            }, wait);
            if (now) result = func.call(this, ...params);
            return result;
        };
    };

    /* 函数的节流 */
    const throttle = function throttle(func, wait) {
        if (typeof func !== 'function')
            throw new TypeError(`${func} must be an function`);
        if (typeof wait !== 'number') wait = 500;
        let timer = null,
            previous = 0
        return function operate(...params) {
            let remaining = wait - (+new Date() - previous),
                result
            if (remaining <= 0) {
                timer = clearTimer(timer)
                result = func.call(this, ...params)
                previous = +new Date()
                return result
            }
            if (!timer) {
                timer = setTimeout(() => {
                    timer = clearTimer(timer)
                func.call(this, ...params)
                previous = +new Date()
                }, remaining)

            }

        }
    };