防抖、节流

315 阅读1分钟

防抖

触发高频事件后n秒内函数只会执行一次,如果n秒内事件被触发,则重新计算事件


immediate = false    先立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。
immediate = false    触发n秒后执行,未执行前再次触发,更新执行时间

function debounce(fn, wait = 1000, immediate = true){
    let timeout = null
    let debounced = function() {
        if(timeout) {
            clearTimeout(timeout)
        }
        if(immediate) {
            if(!timeout) {
                timeout = 1
                fn.apply(this, arguments)
            } else {
                timeout = setTimeout(()=>{
                    timeout = null
                }, wait)
            }
        } else {
            timeout = setTimeout(()=>{
                fn.apply(this, arguments)
                timeout = null
            }, wait)
        }
    }
    
    debounced.cancel = function() {
        clearTimeout(timeout)
        timeout = null
    }
    
    return debounced
}

// 目标事件
function done(){
    console.log('防抖')
}

window.addEventlistener('onmounsemove', debounce(done))

节流

高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率


function throttle(fn, wait = 1000){
    let timeout = null
    let throttled = function() {
        if(timeout) {
            return
        }
        // 添加 async await  兼容异步
        timeout = setTimeout(async ()=>{
            await fn.apply(this, arguments)
            timeout = null
        }, wait)
    }
    
    throttled.cancel = function() {
        clearTimeout(timeout)
        timeout = null
    }
    
    return throttled
}

// 目标事件
function done(){
    console.log('防抖')
}

window.addEventlistener('onmounsemove', throttle(done))