函数节流
const throttle = (fn, wait = 50) => {
let previous = 0
return function(...args) {
let now = +new Date()
if (now - previous > wait) {
previous = now
fn.apply(this, args)
}
}
}
const betterFn = throttle(() => console.log('fn 函数执行了'), 1000)
setInterval(betterFn, 500)
函数防抖
var timer = null;
return function () {
var context = this
var args = arguments
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
var fn = function () {
console.log('boom')
}
setInterval(debounce(fn,500),1000)
setInterval(debounce(fn,2000),1000)