Refactor debounce to simplify, reduce timers, fix bugs.

This commit is contained in:
Brandon Wallace
2016-03-07 12:30:30 -06:00
committed by John-David Dalton
parent 092f90d2fc
commit 864e14cb20
2 changed files with 163 additions and 81 deletions

View File

@@ -4193,6 +4193,76 @@
}, 192);
});
QUnit.test('should honor leading: false when maxWait is not supplied', function(assert) {
assert.expect(6);
var done = assert.async();
var callCount = 0;
var debounced = _.debounce(function(value) {
++callCount;
return value;
}, 32);
// Leading should not fire.
var actual = [debounced(0), debounced(1), debounced(2)];
assert.deepEqual(actual, [undefined, undefined, undefined]);
assert.strictEqual(callCount, 0);
setTimeout(function() {
// Trailing should fire by now.
assert.strictEqual(callCount, 1);
// Do it again.
var actual = [debounced(4), debounced(5), debounced(6)];
// Previous result.
assert.deepEqual(actual, [2, 2, 2]);
assert.strictEqual(callCount, 1);
}, 128);
setTimeout(function() {
assert.strictEqual(callCount, 2);
done();
}, 256);
});
QUnit.test('should honor leading: false when maxWait is supplied', function(assert) {
assert.expect(6);
var done = assert.async();
var callCount = 0;
var debounced = _.debounce(function(value) {
++callCount;
return value;
}, 32, { 'maxWait': 64 });
// Leading should not fire.
var actual = [debounced(0), debounced(1), debounced(2)];
assert.deepEqual(actual, [undefined, undefined, undefined]);
assert.strictEqual(callCount, 0);
setTimeout(function() {
// Trailing should fire by now.
assert.strictEqual(callCount, 1);
// Do it again.
var actual = [debounced(4), debounced(5), debounced(6)];
// Previous result.
assert.deepEqual(actual, [2, 2, 2]);
assert.strictEqual(callCount, 1);
}, 128);
setTimeout(function() {
assert.strictEqual(callCount, 2);
done();
}, 256);
});
QUnit.test('should invoke the `trailing` call with the correct arguments and `this` binding', function(assert) {
assert.expect(2);
@@ -21271,7 +21341,7 @@
});
QUnit.test('should trigger a second throttled call as soon as possible', function(assert) {
assert.expect(2);
assert.expect(3);
var done = assert.async();
@@ -21288,10 +21358,14 @@
throttled();
}, 192);
setTimeout(function() {
assert.strictEqual(callCount, 1);
}, 254);
setTimeout(function() {
assert.strictEqual(callCount, 2);
done();
}, 288);
}, 384);
});
QUnit.test('should apply default options', function(assert) {