Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow _.throttle to function correctly after the system time is updated #1473

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 42 additions & 0 deletions test/functions.js
Expand Up @@ -278,6 +278,26 @@
}, 96);
});

asyncTest('throttle continues to function after system time is set backwards', 2, function() {
var counter = 0;
var incr = function(){ counter++; };
var throttledIncr = _.throttle(incr, 100);
var origNowFunc = _.now;

throttledIncr();
ok(counter == 1);
_.now = function () {
return new Date(2013, 0, 1, 1, 1, 1);
};

_.delay(function() {
throttledIncr();
ok(counter == 2);
start();
_.now = origNowFunc;
}, 200);
});

asyncTest('debounce', 1, function() {
var counter = 0;
var incr = function(){ counter++; };
Expand Down Expand Up @@ -314,6 +334,28 @@
_.delay(function(){ equal(counter, 1, 'incr was debounced'); start(); }, 96);
});

asyncTest('debounce after system time is set backwards', 2, function() {
var counter = 0;
var origNowFunc = _.now;
var debouncedIncr = _.debounce(function(){
counter++;
}, 100, true);

debouncedIncr();
equal(counter, 1, 'incr was called immediately');

_.now = function () {
return new Date(2013, 0, 1, 1, 1, 1);
};

_.delay(function() {
debouncedIncr();
equal(counter, 2, 'incr was debounced successfully');
start();
_.now = origNowFunc;
},200);
});

test('once', function() {
var num = 0;
var increment = _.once(function(){ num++; });
Expand Down
5 changes: 3 additions & 2 deletions underscore.js
Expand Up @@ -695,7 +695,7 @@
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
Expand All @@ -717,7 +717,8 @@

var later = function() {
var last = _.now() - timestamp;
if (last < wait) {

if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
Expand Down