JavaScript中的手寫防抖與節流
阿新 • • 發佈:2021-10-18
函式防抖:函式被觸發後過一段時間再執行,如果在這段時間內又被觸發,則重新計時。
function debounce(func, ms = 1000) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, ms)
}
}
// 測試
const task = () => { console.log('run task') }
const debounceTask = debounce(task, 1000)
window.addEventListener('scroll', debounceTask)
函式節流:函式在一段時間內只能被觸發一次,如果這段時間內被觸發多次,則只有一次生效。
function throttle(func, ms = 1000) {
let canRun = true
return function (...args) {
if (!canRun) return
canRun = false
setTimeout(() => {
func.apply(this, args)
canRun = true
}, ms)
}
}
// 測試
const task = () => { console.log('run task') }
const throttleTask = throttle(task, 1000)
window.addEventListener('scroll', throttleTask)