本篇文章给大家带来的内容是关于节流阀和去抖动的基本实现方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。 节流阀throttle 触发的事件以周期的形式去执行,而非实时。如滴水的水龙头。 function throttle (fn, delay) {
// 利用闭包变量时效性
let timeout
let arg
return function () {
arg = arguments
if (!timeout) {
timeout = setTimeout(() => {
fn.apply(this, arg)
timeout = null
}, delay)
}
}
}
// demo
/*
var test = throttle(function (a) {console.log(a)}, 1000)
test(1) // 不执行
test(2) // 不执行
test(3)
=> 3
test = null // 不需要时释放内存
*/ 去抖动debounce 事件最后一次触发的N毫秒后触发,如电梯门。 function debounce (fn, delay){
let timeout
return function(){
const args = arguments
clearTimeout(timeout)
timeout = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// 用法同throttle 以上就是节流阀和去抖动的基本实现方法介绍的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |