防抖、节流

// 节流
export function throttle({ delay = 300, callback = () => { } }) {
    return function (...args) {
        const { isRunning } = throttle
        if (isRunning) return
        throttle.isRunning = true
        setTimeout(() => {
            callback(...args)
            throttle.isRunning = null
        }, delay)
    }
}
// 防抖
export function debounce({ delay = 300, callback = () => { } }) {
    return function (...args) {
        const { lastid } = debounce
        lastid && clearTimeout(lastid)
        debounce.lastid = setTimeout(() => {
            callback(...args)
            // 释放内存
            debounce.lastid = null
        }, delay)
    }
}

使用方法:

    debounce({ delay: 300, callback: () => {
        // TODO 防抖后回调...
    } })()

 

posted @ 2023-02-28 11:36  ^柒  阅读(24)  评论(0)    收藏  举报