
实现防抖函数(debounce)
js
let debounce = (fn, time = 1000) => {
let timeLock = null
return function (...args) {
clearTimeout(timeLock)
timeLock = setTimeout(() => {
fn(...args)
}, time)
}
}js
const debounce = (func, wait) => {
// 缓存一个定时器
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}js
function debounce(fn, delay = 300) {
// 默认300毫秒
// 缓存一个定时器
let timer
// 这里返回的函数是每次用户实际调用的防抖函数
// 如果已经设定过定时器了就清空上一次的定时器
// 开始一个新的定时器。延迟执行用户传入的方法
return function () {
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
