1.函数节流:当一个函数会被频繁执行时,在一定时间段内只执行第一次
function throttle (fn, delay) {
let lastTime = 0
return function () {//使用闭包缓存lastTime
let currentTime = Date.now()
if(currentTime - lastTime > delay){
fn()
lastTime = currentTime
}
}
}
1.函数防抖:当一个函数会被频繁执行时,在一定时间段内只执行最后一次
function debounce (fn, delay) {
let timeId = null
return function () {//使用闭包缓存timeId
clearTimeout(timeId)
timeId = setTimeout(function(){
fn()
} ,delay)
}
}