防抖节流常用场景

2019-12-17  本文已影响0人  _一九九一_

节流

规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

场景

function throttle(fn, delay) {
    let previous = 0;
    // 使用闭包返回一个函数并且用到闭包函数外面的变量previous
    return function() {
        let _this = this;
        let args = arguments;
        let now = new Date();
        if(now - previous > delay) {
            fn.apply(_this, args);
            previous = now;
        }
    }
}

防抖

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

场景

function debounce(fn, delay) {
    let timer; // 维护一个 timer
    return function () {
        let _this = this; // 取debounce执行作用域的this
        let args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            fn.apply(_this, args); // apply指向调用debounce的对象,相当于_this.fn(args);
        }, delay);
    };
}
上一篇 下一篇

猜你喜欢

热点阅读