h bob
h bob

Reputation: 3780

Underscore debounce with arguments

Suppose I have this event handler:

var mousewheel = function (e) { /* blah */ };

But, I want to debounce it. So I do this, which works as expected:

var mousewheelDebounced = _.debounce(mousewheel, 500);
$(document).on("mousewheel", function (e) {
  e.preventDefault();
  mousewheelDebounced(e);
}

But this doesn't work as expected:

$(document).on("mousewheel", function (e) {
  e.preventDefault();
  _.debounce(mousewheel, 500)(e);
}

I prefer the compactness of the second form. But no debouncing occurs.

I assume no reference to the mousewheelDebounced remains, so the underlying handler is called every time. Is that the reason? How can I clean up this code, if possible?

You can see a fiddle here.

Upvotes: 4

Views: 2885

Answers (1)

dfsq
dfsq

Reputation: 193271

On each mousewheel event (which occurs very often) you create a new version of debounce function. This function has no history, and doesn't know that on previous event there was another one created. So it just runs. That's why you should go with the first version.

Upvotes: 5

Related Questions