节流阀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