节流防抖及加强版

116 阅读1分钟
function throttle (fn, internal) {
    let last=0
    return function() {
        const context = this
        const args = arguments
        const now = + new Date()
        if(now - last > internal) {
            last = now
            fn.apply(context, args)
        }
    }
}


function debounce(fn, internal) {
    let timer = void 0
    return function() {
        const context = this
        const args = arguments
        clearTimeout(timer)
        timer = setTimeout(() => {
            clearTimeout(timer)
            fn.apply(context, args)
        }, internal)
    }
}

function strongThrottle (fn, internal) {
    let last = 0
    let timer = void 0
    return function() {
        const context = this
        const args = arguments
        const now = + new Date()
        if (now - last < internal) {
            clearTimeout(timer)
            timer = setTimeout(() => {
                last = now
                fn.apply(context, args)
            }, internal)
        } else {
            last = now
            fn.apply(context, args)
        }
    }
}