帮我写一个防抖节流代码示例
时间: 2023-03-14 10:09:35 浏览: 92
// 以下是一个防抖节流代码示例:// 防抖函数
function debounce(func, delay) {
let timer = null
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}// 节流函数
function throttle(func, wait) {
let context, args, prevArgs, argsChanged, result
let previous = 0
return function() {
let now, remaining, argsChanged = false
if (wait) {
now = Date.now()
remaining = wait - (now - previous)
}
args = arguments
argsChanged = JSON.stringify(args) !== JSON.stringify(prevArgs)
prevArgs = {...args}
if (argsChanged && remaining <= 0 || !wait) {
result = func.apply(context, args)
previous = now
}
return result
}
}
阅读全文