防抖和节流

78 阅读1分钟

防抖,本质:延迟事件的执行;常见场景:input搜索事件

debounce (n) {
    let timer
    // n秒后执行函数,在 n 秒内又触发了事件,重新计算函数时间
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
        // doing somthing
        timer = null
    }, n)
},

防抖函数的封装:

debounce (fun, time) {
    let timer;
    return function () {
        let self = this
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fun.apply(self, [...arguments])
        }, time);
    }
}

节流, 本质:减少事件的执行;常见的应用场景:鼠标的mouseMove事件、滚轮滚动事件

throttle (n) {
    // 连续触发事件n秒内只执行一次,稀释事件的执行
    let timer
    if (!timer) {
        timer = setTimeout(() => {
            // doing somthing
            timer = null
        }, n)
    }
}

节流函数的封装

throttle (fun, time) {
    let timer;
    return function() {
        let self = this;
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
                fun.apply(self, [...arguments])
            }, time)
        }
    }
}