节流防抖

2022/2/20 JavaScript

# 1. 节流防抖是什么

  • 本质上是优化高频率执行代码的一种手段。如:浏览器的 resizescrollkeypressmousemove 等事件在触发时,会不断地调用绑定在事件上的回调函数,极大地浪费资源,降低前端性能。
  • 为了优化体验,需要对这类事件进行调用次数的限制,对此我们就可以采用throttle(节流)和debounce(防抖)的方式来减少调用频率。

# 2. 定义

  • 节流: n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效。(冷却)
  • 防抖: n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时。(回城)
  • 一个经典的比喻:想象每天上班大厦底下的电梯。把电梯完成一次运送,类比为一次函数的执行和响应。假设电梯有两种运行策略 debouncethrottle,超时设定为15秒,不考虑容量限制。【1】电梯第一个人进来后,15秒后准时运送一次,这是节流。【2】电梯第一个人进来后,等待15秒。如果过程中又有人进来,15秒等待重新计时,直到15秒后开始运送,这是防抖。

# 3. 代码实现

# 节流

  • 完成节流可以使用时间戳与定时器的写法。
  • 使用时间戳写法,事件会立即执行,停止触发后没有办法再次执行。
function throttled1(fn, delay = 500) {
    let oldtime = Date.now()
    return function (...args) {
        let newtime = Date.now()
        if (newtime - oldtime >= delay) {
            fn.apply(null, args)
            oldtime = Date.now()
        }
    }
}
1
2
3
4
5
6
7
8
9
10
  • 使用定时器写法,delay毫秒后第一次执行,第二次事件停止触发后依然会再一次执行。
function throttled2(fn, delay = 500) {
    let timer = null
    return function (...args) {
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(this, args)
                timer = null
            }, delay);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
  • 可以将时间戳写法的特性与定时器写法的特性相结合,实现一个更加精确的节流。
function throttled(fn, delay) {
    let timer = null
    let starttime = Date.now()
    return function () {
        let curTime = Date.now() // 当前时间
        let remaining = delay - (curTime - starttime)  // 从上一次到现在,还剩下多少多余时间
        let context = this
        let args = arguments
        clearTimeout(timer)
        if (remaining <= 0) {
            fn.apply(context, args)
            starttime = Date.now()
        } else {
            timer = setTimeout(fn, remaining);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 防抖

  • 简单版本的实现。
function throttled(fn, delay) {
    let timer = null
    let starttime = Date.now()
    return function () {
        let curTime = Date.now() // 当前时间
        let remaining = delay - (curTime - starttime)  // 从上一次到现在,还剩下多少多余时间
        let context = this
        let args = arguments
        clearTimeout(timer)
        if (remaining <= 0) {
            fn.apply(context, args)
            starttime = Date.now()
        } else {
            timer = setTimeout(fn, remaining);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • 防抖如果需要立即执行,可加入第三个参数用于判断。
function debounce(func, wait, immediate) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout); // timeout 不为null
        if (immediate) {
            let callNow = !timeout; // 第一次会立即执行,以后只有事件执行后才会再次触发
            timeout = setTimeout(function () {
                timeout = null;
            }, wait)
            if (callNow) {
                func.apply(context, args)
            }
        }
        else {
            timeout = setTimeout(function () {
                func.apply(context, args)
            }, wait);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 4. 应用场景

  • 节流在间隔一段时间执行一次回调的场景有:【1】滚动加载,加载更多或滚到底部监听。【2】搜索框,搜索联想功能。
  • 防抖在连续的事件,只需触发一次回调的场景有:【1】搜索框搜索输入。【2】手机号、邮箱验证输入检测。【3】窗口大小resize,只需窗口调整完成后,计算窗口大小,防止重复渲染。
Last Updated: 2023/04/22, 23:39:26
彩虹
周杰伦