2015-11-18 79 views
0

用例Javascript关键事件 - 只有在重复关键事件时才会发生?

  1. 我有(如在FB信使)的个人或团体的列表(左侧窗格)
  2. 。当切换人,我加载消息(API调用)。
  3. 如果我快速按下箭头,那么不是为每个人进行API调用,而只想加载我暂停和等待的人。
  4. 目前我正在剔除300ms来实现这一目标。

    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. 当我在消息1 - M1细节加载
  2. 当我按下键快 - M2将加载,然后去反弹会发生下一条消息)

我想避免这个M2负载。我不确定是否可以在同一个流程中混合使用debouce和非debounce

+0

你能仅仅存储在一个物体或事物的关键事件值然后让debounce代码首先在debouncing之前检查该对象的值?就像,它的前一个关键值与当前事件值相同,然后消除,否则它不会。 – Pytth

回答

0

而不是“debounce”,您可能正在寻找一些能够在调用函数之前启动超时并等待一段时间在通过最后一个参数这里是一个quick'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); 
     } 
    } 
} 

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