简洁版:
function throttle(fn, content){
clearTimeout(fn.timer);
fn.timer = setTimeout(function(){
fn.call(content)
},1000)
}
第一次调用有延迟。
时间戳方式:
function throttle(fn, gapTime) { if (gapTime == null || gapTime == undefined) { gapTime = 1500 } let _lastTime = null return function () { let _nowTime = + new Date() if (_nowTime - _lastTime > gapTime || !_lastTime) { fn.apply(this, arguments) //将this和参数传给原函数 _lastTime = _nowTime } } }
定时器方式:
function throttle ( fn, delay){ var timer; var isThrottle = false; return function (){ var _this = this var args = arguments if(!isThrottle){ isThrottle = true fn.apply(_this,args) timer = setTimeout(()=>{ clearTimeout(timer) isThrottle = false },delay || 1000) } } }
调用方式:
Page({ ... handle: throttle(function () { console.log(this) }, 500) ... })