scarcoco / projx

5 stars 0 forks source link

debounce & throttle #33

Open scarcoco opened 4 years ago

scarcoco commented 4 years ago

debounce & throttle

如果依赖 callback 的返回值,则有问题。

/**
 * debounce 函数
 * @param {Function} callback 
 * @param {Number} delay 
 */
function debounce(callback, delay) {
    let ret = null
    return function () {
        if (ret) {
            clearTimeout(ret)
            ret = null
        }
        ret = setTimeout(() => {
            callback.apply(this, arguments)
        }, delay)
    }
}

/**
 * throttle 函数
 * @param {Function} callback 
 * @param {Number} ms 
 */
function throttle(callback, ms) {
    ms = ms || 50

    let prev = 0, timeout = null
    function cancel() {
        clearTimeout(timeout)
        timeout = null
    }

    function newCallback () {
        const now = Date.now()
        const rest = ms - (now - prev)
        cancel()

        if (rest <= 0) {
            prev = now
            return callback.apply(this, arguments)
        } else {
            timeout = setTimeout(() => {
                callback.apply(this, arguments)
            }, rest)
        }
    } 
    newCallback.cancel = cancel
    return newCallback
}