函数防抖(debounce):
限制函数重复调用,只执行最后的一次。
某个函数存在重复执行的可能(比如dom事件处理函数)。函数在调用时使用延时执行(setTimeout)然后在后续重复调用的时候,都会取消上一次的执行,之后重新定时执行。
代码:
<button id="btn">btn</button>
let debounceTimeout
function debounce(fn, timeout) {
clearTimeout(debounceTimeout)
debounceTimeout = setTimeout(() => {
fn()
}, timeout)
}
function httpAction() {
console.log('httpAction!');
}
document.getElementById("btn").addEventListener("click", function () {
debounce(httpAction, 1000)
})
函数节流
在函数防抖中,连续点击不管几次,都只会执行最后的一次。在上面防抖的例子中,我每800毫秒就重复change,那么httpAction只有在我停的时候才会调用一次。假设我想让他在重复时有个保底1秒执行一次。
代码:
<button id="btn">btn</button>
function throttle(fn, delay) {
clearTimeout(fn.timer)
fn.currentTime = Date.now()
if (!fn.startTime) {
fn.startTime = fn.currentTime
}
if (fn.currentTime - fn.startTime >= delay) {
fn.call()
fn.startTime = fn.currentTime
} else {
fn.timer = setTimeout(function () {
fn.call()
fn.startTime = null
}, delay)
}
}
function httpAction() {
console.log('httpAction!');
}
document.getElementById("btn").addEventListener("click", function () {
throttle(httpAction, 1000)
})