手写防抖节流函数
防抖函数
function debounce(fn, t) {
let timeId
return function () {
// 如果有定时器就清除
if (timeId) clearTimeout(timeId)
// 开启定时器 200
timeId = setTimeout(function () {
fn()
}, t)
}
}
// 节流函数 throttle
function throttle(fn, t) {
// 起始时间
let startTime = 0
return function () {
// 得到当前的时间
let now = Date.now()
// 判断如果⼤于等于 500 采取调⽤函数
if (now - startTime >= t) {
// 调⽤函数
fn()
// 起始的时间 = 现在的时间 写在调⽤函数的下⾯
startTime = now
}
}
}
浙公网安备 33010602011771号