• debounce 防抖

    简单来说,就是放抖动。

    当持续触发事件时,debounce会合并事件且不会去触发事件,当一定时间内没有触发再这个事件时,才真正去触发事件。

    1
    debounce(fn, 1000); //1秒内没有触发这个事件才执行

    下面是debounce的简单实现:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    function debounce(fn, delay) {
    let timer;
    let ctx;
    let args;
    const execute = function() {
    fn.apply(ctx, args);
    };
    return function() {
    ctx = this;
    args = arguments;
    if (timer) {
    clearTimeout(timer);
    }
    timer = setTimeout(execute, delay);
    };
    }
  • throttle 节流

    当持续触发事件时,保证隔间时间触发一次事件。

    1
    throttle(fn, 1000); // 一秒内只触发一次。需要注意的是,比如你一秒内按了两下以上,那么将触发两次

    下面是throttle的简单实现:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    function throttle(fn, delay) {
    let ctx;
    let args;
    let timer;
    let now;
    let previous;
    const execute = function() {
    fn.apply(ctx, args);
    previous = now;
    };
    return function() {
    ctx = this;
    args = arguments;
    now = Date.now();
    if (timer) {
    clearTimeout(timer);
    }
    const diff = now - (previous + delay);
    if (previous) {
    if (diff >= 0) {
    execute();
    } else {
    timer = setTimeout(execute, -diff);
    }
    } else {
    execute();
    }
    };
    }

    根据实际业务场景,合理的利用debounce(防抖)和throttle(节流)可以优化性能和提高用户体验。两者间的核心区别就在于持续触发事件时,前者合并事件并在最后时间去触发事件,而后者则是隔间时间触发一次。

  • 参考

    https://segmentfault.com/a/1190000005926579