通过参数调用去抖函数 [英] Debounce function calls by their arguments
问题描述
David Walsh在此处实施了很好的辩论。
David Walsh has a great debounce implementation 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);
};
};
我在生产中使用它并且效果很好。
I am using it in production and it works great.
现在我遇到了一个更复杂的去抖动案例。
Now i have encountered a bit more complex case of debounce need.
我有一个事件用这样的参数调用一个事件处理程序:
$(elem).on('onSomeEvent',(e)=> {handler(eX)});
I have an event that calls an event handler with a param like this: $(elem).on('onSomeEvent', (e) => {handler(e.X)} );
我很乐意经常触发这个事件并且每秒调用处理程序1000次。我不需要去除处理程序本身。
但在我的情况下,对于每个eX,我希望在一段时间内只调用一次,比如说250ms。
I am ok with this event being triggered frequently and calling the handler even 1000 times a second. I don't need to debounce the handler itself. But in my case, for each e.X, i want it to be called just once in a period, say 250ms.
我在想创建一个两个eX保持x和最后运行时间的维数组,但我不想声明任何全局变量。
I was thinking of creating a two dimensional array which holds the x and the last run time, but i don't want to declare any global variables.
任何想法?
*编辑*
阅读@Tim Vermaelen后,我已实施了像这样,它工作:
After reading @Tim Vermaelen answer i have implemented it like this, and it worked:
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 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。如果我理解正确的话,你必须将它包裹在处理程序(eX)
中。
I don't believe there's much difference with your solution except for the fact I can add unique id's in the events. You'll have to wrap this around handler(e.X)
if I understand correctly.
debounce(func_to_param, 250, 'mousewheel');
debounce(func_to_param, 250, 'scrolling');
这篇关于通过参数调用去抖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!