Skip to content

Commit

Permalink
Merge pull request jashkenas#1629 from dontfidget/re-entrant
Browse files Browse the repository at this point in the history
fix throttle and debounce to be re-entrant
  • Loading branch information
jashkenas committed May 7, 2014
2 parents 530fc78 + fd69f5b commit 29a973f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
45 changes: 45 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,29 @@
}, 200);
});

asyncTest('throttle re-entrant', 2, function() {
var sequence = [
['b1', 'b2'],
['c1', 'c2']
];
var value = '';
var throttledAppend;
var append = function(arg){
value += this + arg;
var args = sequence.pop()
if (args) {
throttledAppend.call(args[0], args[1]);
}
};
throttledAppend = _.throttle(append, 32);
throttledAppend.call('a1', 'a2');
equal(value, 'a1a2');
_.delay(function(){
equal(value, 'a1a2c1c2b1b2', 'append was throttled successfully');
start();
}, 100);
});

asyncTest('debounce', 1, function() {
var counter = 0;
var incr = function(){ counter++; };
Expand Down Expand Up @@ -369,6 +392,28 @@
}, 200);
});

asyncTest('debounce re-entrant', 2, function() {
var sequence = [
['b1', 'b2']
];
var value = '';
var debouncedAppend;
var append = function(arg){
value += this + arg;
var args = sequence.pop()
if (args) {
debouncedAppend.call(args[0], args[1]);
}
};
debouncedAppend = _.debounce(append, 32);
debouncedAppend.call('a1', 'a2');
equal(value, '');
_.delay(function(){
equal(value, 'a1a2b1b2', 'append was debounced successfully');
start();
}, 100);
});

test('once', function() {
var num = 0;
var increment = _.once(function(){ num++; });
Expand Down
12 changes: 9 additions & 3 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,9 @@
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
if (!timeout) {
context = args = null;
}
};
return function() {
var now = _.now();
Expand All @@ -692,7 +694,9 @@
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
if (!timeout) {
context = args = null;
}
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
Expand All @@ -716,7 +720,9 @@
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
if (!timeout) {
context = args = null;
}
}
}
};
Expand Down

0 comments on commit 29a973f

Please sign in to comment.