防抖和节流

1、使用场景
持续出发的事件,如resize,scroll,mousemove,文本输入等

防抖(debounce)

触发事件后n秒内仅执行一次,如果n秒内又触发了事件,则会重新计算函数执行时间

/*
* 非立即执行 (debounce1):
* 触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间
* */
function debounce1(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}
/*
* 立即执行 (debounce2):
* 触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数
* */
function debounce2(func,wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);

        let callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, wait)

        if (callNow) func.apply(context, args)
    }
}

节流(throttle)

连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率

// 时间戳版
function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

// 定时器版
function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}

你可能感兴趣的:(防抖和节流)