節流函數

概念解讀

函數節流是指必定時間內js方法只跑一次。
生活例子:人的眨眼睛,就是必定時間內眨一次。app

應用場景:

一、鼠標不斷點擊觸發,mousedown(單位時間內只觸發一次)。
二、監聽滾動事件(它是一個高頻觸發對事件),好比是否滑到底部自動加載更多,用throttle來判斷。函數

函數:

function throttle(fun, delay) {
    let last, deferTimer
    return function (args) {
        let that = this
        let _args = arguments
        let now = +new Date()
        if (last && now < last + delay) {
            clearTimeout(deferTimer)
            deferTimer = setTimeout(function () {
                last = now
                fun.apply(that, _args)
            }, delay)
        }else {
            last = now
            fun.apply(that,_args)
        }
    }
}
相關文章
相關標籤/搜索