节流函数-throttleCall

161 阅读1分钟

节流函数在lodash中有现成的工具函数,有时希望精简代码可以自己diy一个

var throttleCall=function(fn,interval){
    var enabled=true
    return function(){
        if(enabled){
            fn()
            enabled=false
            setTimeout(function(){enabled=true},interval)
        }
    }
}

test:

var fn=function(){
    console.log('hello')
}
var throttleFn=throttleCall(fn,3000)
throttleFn()
throttleFn()
throttleFn()

输出:

hello