admin管理员组

文章数量:1430807

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 plex case of debounce need.

I have an event that calls an event handler with a param like this: $(elem).on('onSomeEvent', (e) => {handler(e.X)} );

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.

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.

Any ideas?

* EDIT *

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);
        };
    };

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 plex case of debounce need.

I have an event that calls an event handler with a param like this: $(elem).on('onSomeEvent', (e) => {handler(e.X)} );

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.

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.

Any ideas?

* EDIT *

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);
        };
    };
Share Improve this question edited Dec 12, 2016 at 16:15 Dorad asked Dec 12, 2016 at 15:30 DoradDorad 3,6935 gold badges52 silver badges77 bronze badges 4
  • var timeout isn't a global variable in the original code either? – Bergi Commented Dec 12, 2016 at 16:54
  • Seems to be unfortunately – Dorad Commented Dec 12, 2016 at 18:22
  • Not unfortunate, but exactly what you want? – Bergi Commented Dec 12, 2016 at 18:30
  • Apparently, as it made the work – Dorad Commented Dec 12, 2016 at 19:20
Add a ment  | 

1 Answer 1

Reset to default 5

What I always use is the following:

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

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');

本文标签: javascriptDebounce function calls by their argumentsStack Overflow