0

用例

  1. 我有一个人或组列表(如在 FB Messenger 中)(左窗格)
  2. 当我换人时,我会加载消息(API 调用)。
  3. 如果我快速按下向下箭头,那么我不想为每个人进行 API 调用,而是只想加载我暂停并等待的人。
  4. 目前我正在去抖 300 毫秒来实现这一点。

    handleSwitchKeyEvent: function() {
        if (this.pendingLoad) {
            // Still pending continue to debounce
            clearTimeout(this.pendingLoad);
            fn = this.loadContent;
        } else {
            // No longer pending - So load data immediately
            this.loadContent();
        }
    
        // Delay the load
        this.pendingLoad = setTimeout(function () {
            clearTimeout(this.pendingLoad);
            this.pendingLoad = 0;
            fn && fn.call(this);
        }, 300);
    }
    

问题

  1. 当我在 Message1 时 - 已加载 M1 详细信息
  2. 当我快速按键时 - M2 将加载,然后下一条消息会发生反跳)

我想避免这种 M2 负载。我不确定是否可以在同一流程中混合去抖动和非去抖动

4

1 回答 1

1

您可能正在寻找的不是“去抖动”,而是在使用传入的最后一个参数调用函数之前启动超时并等待设定的持续时间。这是一个快速的'n'dirty缓冲函数(未经测试):

function buffer( fn, duration ) {
    // Store a timeout id and last args called with
    var buffer;
    var lastArgs;
    return function( ) {
        // The last args will be used
        lastArgs = arguments;
        // If buffer hasn't started, kick it off
        if (!buffer) {
            buffer = setTimeout(function() {
                // After duration, call the function with args
                // Reset buffer
                fn.apply(null, lastArgs);
                buffer = null;
            }, duration);
        }
    }
}

编辑:忘记清除缓冲区变量

于 2015-11-18T21:50:02.997 回答