节流 throttle
function throttle(fn , delay) {
let timer = null
return function() {
let arg = arguments
if(!timer) {
timer = setTimeout(()=> {
fn.apply(this, arg)
clearTimeout(timer)
timer = null
}, delay)
}
}
}
let throttleFunc = throttle(function(a, b) {
console.log(a, b, 'throttle----')
}, 1000)
setInterval(() => {
console.log('setInerval')
throttleFunc(1, 2)
}, 500)
防抖
function debounce(fn, delay) {
let timer = null
return function() {
let arg = arguments
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arg)
}, delay)
}
}
let debounceFunc = debounce(function(a, b) {
console.log(a, b, 'debounce')
}, 500)
setInterval(() => {
console.log('interval---')
debounceFunc(1, 2)
}, 400)
// 如果间隔小于delay, timer会被无限重置,不会执行debouceFunc