函数防抖、函数节流
函数消抖(debounce)
当调用函数 n 秒后,才会执行该动作,若在这 n 秒内又调用该函数则将取消前一次并重新计算执行时间
代码原理
设定一个全局变量保存定时器,事件触发时,判断定时器是否存在,存在时,消除定时器,不存在时,重新设定定时器,确保一段时间内,只存在一个定时器。
伪代码
function _log() {
console.log('log')
}
function _debounce(fn, delay) {
var timer = null
return function() {
timer && clearTimeout(timer)
timer = setTimeout(function() {
fn()
}, delay)
}
}
window.onresize = _debounce(_log, 1000)
函数节流(throttle)
函数预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期
代码原理
定义一个时间周期,当调用动作频率小于定义的时间周期,则进入下一周期,不会频繁触发
伪代码
function _log() {
console.log('log')
}
function _throttle(method, duration) {
var begin = new Date()
return function() {
var _this = this,
_args = arguments,
current = new Date()
if (current - begin >= duration) {
method.apply(_this, _args)
begin = current
}
}
}
window.onresize = _throttle(_log, 1000)