2016-12-12 95 views
3

大衛·沃爾什有很好的去抖實現here去抖功能調用

// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. If `immediate` is passed, trigger the function on the 
// leading edge, instead of the trailing. 
function debounce(func, wait, immediate) { 
    var timeout; 
    return function() { 
     var context = this, args = arguments; 
     var later = function() { 
      timeout = null; 
      if (!immediate) func.apply(context, args); 
     }; 
     var callNow = immediate && !timeout; 
     clearTimeout(timeout); 
     timeout = setTimeout(later, wait); 
     if (callNow) func.apply(context, args); 
    }; 
}; 

我在生產中使用它,它工作的很棒。

現在我遇到了一個更復雜的反彈需要的情況。我有一個事件,調用一個像這樣的參數的事件處理程序: $(elem).on('onSomeEvent',(e)=> {handler(e.X)});

我很高興這個事件被頻繁觸發,甚至每秒鐘調用處理程序1000次。我不需要去掉處理程序本身。 但在我的情況下,對於每個e.X,我希望它在一段時間內只被調用一次,比如說250ms。

我想創建一個包含x和最後運行時間的二維數組,但我不想聲明任何全局變量。

任何想法?

*編輯*

閱讀@Tim費爾馬倫答案我已經實現了它這個樣子,和它的工作後:

export function debounceWithId(func, wait, id, immediate?) { 
     var timeouts = {}; 
     return function() { 
      var context = this, args = arguments; 
      var later = function() { 
       timeouts[id] = null; 
       if (!immediate) func.apply(context, args); 
      }; 
      var callNow = immediate && !timeouts[id]; 
      clearTimeout(timeouts[id]); 
      timeouts[id] = setTimeout(later, wait); 
      if (callNow) func.apply(context, args); 
     }; 
    }; 
+0

'var timeout'不是原始代碼中的全局變量嗎? – Bergi

+0

似乎是不幸的 – Dorad

+0

不是不幸,但正是你想要的? – Bergi

回答

3

我一直用的是以下幾點:

var debounce = (function() { 
    var timers = {}; 

    return function (callback, delay, id) { 
     delay = delay || 500; 
     id = id || "duplicated event"; 

     if (timers[id]) { 
      clearTimeout(timers[id]); 
     } 

     timers[id] = setTimeout(callback, delay); 
    }; 
})(); // note the call here so the call for `func_to_param` is omitted 

我不認爲與您的解決方案有很大的區別,除了事實上我可以在事件中添加唯一的ID。如果我理解正確,你將不得不圍繞handler(e.X)進行包裝。

debounce(func_to_param, 250, 'mousewheel'); 
debounce(func_to_param, 250, 'scrolling'); 
+1

我現在正在嘗試,並會讓你知道。 – Dorad

+1

工作就像一個魅力。我張貼我的修改爲他人。 – Dorad