节流函数 n秒内只执行一次,如果重复触发则只执行一次
function throttle(fn, delay = 300) {
let oldTime = Date.now()
return function (...args) {
let newTime = Date.now()
if (newTime - oldTime >= delay) {
fn.apply(fn, args)
oldTime = Date.now()
}
}
}
防抖:n秒后才执行,如果触发则重新计时
function debounce(fn, wait) {
let timer
return function () {
let context = this
let args = arguments
clearTimeout(timeout)
timer = setTimeout(() => {
fn.apply(context, args)
}, wait);
}
}
function debounce(fn, delay) {
let timer = null
return function debounceFn(...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, ...args)
}, delay);
}
**}**