防抖
js
function debounce(fn, delayTime) {
let timer = null;
return function () {
let args = arguments;
let context = this;
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(context, args)
}, delayTime)
}
}
节流
时间戳写法
js
function throttle(fn, delayTime) {
let pre = null
return function () {
let args = arguments;
let context = this;
let now = Date.now()
if (now - pre >= delayTime) {
fn.apply(context, args)
pre = now
}
}
}
定时器写法
js
function throttle(fn, delayTime) {
let timer = null
return function () {
let args = arguments;
let context = this;
if (!timer) {
setTimeout(() => {
fn.apply(context, args)
timer = null;
}, delayTime)
}
}
}