防抖动是将 多次执行 变为 最后一次执行
节流是将 多次执行 变成 每隔一段时间执行
防抖
每次触发事件时都取消之前的延时调用方法,多次调用函数只返回是最后一次调用的结果
function debounce(fn, wait, immediate) {
let timer = null
return function (...args) {
// 是否第一次执行
if (!timer && immediate) {
fn.apply(this, args)
}
// 每当触发函数的时候 ,把前一个setTimeout clear 掉
clearTimeout(timer)
// 然后重新建一个延时器触发, 这样就实现了最后一次调用
timer = setTimeout(() => {
fn.apply(this, args)
}, wait)
}
}
测试
节流
function throttle(fn, wait) {
let last = 0
return function (...args) {
if (Date.now() - last >= wait) {
last = Date.now()
fn.apply(this, args)
}
}
}
测试
document.onclick = throttle(function () {
console.log('lallaal')
}, 1000)