-_-#【Better Code】throttle / debounce

浅谈javascript的函数节流

javascript函数的throttle和debounce

throttle 疯狂触发事件,固定步调执行

debounce 疯狂触发事件,不会执行

  

var resizeTimer = null
window.onresize = function() {
    if (resizeTimer) {
        clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(function() {
        console.log(1)
    }, 500)
}

  

var debounce = function(func, threshold, execAsap) {  
    var timeout
    return function debounced() {  
        var obj = this
        var args = arguments
        function delayed() {  
            if (!execAsap) {
                func.apply(obj, args)
            }  
            timeout = null
        }
        if (timeout) { // 时间少于threshold timeout一直clearTimeout 不会执行delayed
            clearTimeout(timeout)
        } else if (execAsap) { // 直接执行还是延迟执行
            func.apply(obj, args)
        } 
        timeout = setTimeout(delayed, threshold || 100)
    }
}

window.onresize = debounce(function() {
    console.log(1)
}, 200, true)
原文地址:https://www.cnblogs.com/jzm17173/p/3459525.html