手写工具函数系列--手写节流函数

37 阅读1分钟

节流跟防抖有什么区别呢? 节流是高频事件在固定时间内只触发一次,如果过了这个时间,高频事件还继续,会重新计时,在这个固定时间内再触发一次。
防抖则是在固定时间内,只会在高频事件最后一次那次触发。
节流函数跟防抖函数一样,也都用到了闭包。
以下是具体实现

function coloring(a, b, c) {
    console.log(a, b, c);
}
function thorttle(func, delay) {
    const args = Array.prototype.slice.call(arguments, 2)
    let timer;
    return function () {
        let context = this
        if (timer) return
        timer = setTimeout(function () {
            func.apply(context, args)
            timer = null
        }, delay)
    }
}
window.addEventListener('resize', thorttle(coloring, 1000, 1, 2, 3))

对于高频click事件、scroll、输入框的change、resize等等场景,可以根据具体场景需求来使用节流和防抖。