// 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);
};
};
'var timeout'不是原始代碼中的全局變量嗎? – Bergi
似乎是不幸的 – Dorad
不是不幸,但正是你想要的? – Bergi