js防抖和节流

1. 什么是节流(throttle)和防抖(debounce)

  1. 概念
    • 节流(throttle):是函数在一定时间内,不管调用了多少次,实际只会在最后的时候执行一次
    • 防抖(debounce):是函数在一定时间内,每次调用,都会重置倒计时,直到规定时间内没有再次调用,才会执行
  2. 区别
    这里以关门当作函数执行前等待时间时的操作;以发车继续运行下一步为实际执行函数
    • 节流类似于地铁,在指定时间后,一定会关门发车,不管是否再有人想进来,最终只会执行一次关门发车的行为
    • 防抖类似于电梯,电梯需要在n秒后关门,然后才会运行,但是如果有人中途按下门外按钮,会重置关门这个行为,直到没有人上电梯,才会继续运行。

2. 如何实现节流

function throttle(fn, timeout) {
    let timer = null;

    return function() {
         if(!timer) {
            timer = setTimeout(()=>{
                // 解决this指向和arguments,因为setTimeout和setInterval中的this指向window
                fn.apply(this, arguments);
                timer = null;
            }, timeout);
        }
    }
}
// 使用
const throttledFn = throttle((a, b, c) => console.log(a, b, c), 3000);

3. 如何实现防抖

function debounce(fn, timeout) {
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            // 解决this指向和arguments,因为setTimeout和setInterval中的this指向window
            fn.apply(this, arguments);
        }, timeout);
    }
}
// 使用
const debouncedFn = debounce((a, b) => console.log(a, b), 2000);

4. CSS版节流

第一种思路:

button{
  animation: throttle 2s step-end forwards;
}
button:active{
  animation: none;
}
@keyframes throttle {
  from {
    pointer-events: none;
  }
  to {
    pointer-events: all;
  }
}

另一种思路:
image

5. 应用场景

  1. 防抖的应用场景:搜索框的输入联想、表单校验,窗口大小调整的回调 等等;
  2. 节流的应用场景:懒加载、滚动加载、加载更多或监听滚动条位置、防止表单重复提交 等等;
posted @ 2023-05-26 09:24  pangqianjin  阅读(47)  评论(0编辑  收藏  举报