1. debounce()防抖函数🍊
某个函数在短时间内只执行最后一次。
function debounce(fn,delay = 200) {
if(typeof fn !== 'function'){
return TypeError('fn is not a function')
}
let lastfn = null
return function(...args) {
if(lastfn){
clearTimeout(lastfn)
}
lastfn = setTimeout(() => {
lastfn = null
fn.call(this,...args)
},delay)
}
}
2. throttle()节流函数🍊
某个函数在指定时间段内只执行第一次,直到指定时间段结束,周而复始。
function throttle(fn, delay = 200) {
let flag = false
return function (...args) {
if (!flag) {
flag = true
setTimeout(() => {
flag = false
fn.call(this,...args)
},delay)
}
}
}