Skip to content

Commit 311b04e

Browse files
authoredDec 7, 2020
Merge pull request #2892 from kritollm/master
Reimplementing timer optimization #1269
2 parents d10beb9 + 6568211 commit 311b04e

File tree

5 files changed

+57
-42
lines changed

5 files changed

+57
-42
lines changed
 

‎modules/debounce.js

+19-14
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,39 @@
11
import restArguments from './restArguments.js';
2-
import delay from './delay.js';
2+
import now from './now.js';
33

44
// When a sequence of calls of the returned function ends, the argument
55
// function is triggered. The end of a sequence is defined by the `wait`
66
// parameter. If `immediate` is passed, the argument function will be
77
// triggered at the beginning of the sequence instead of at the end.
88
export default function debounce(func, wait, immediate) {
9-
var timeout, result;
9+
var timeout, previous, args, result, context;
1010

11-
var later = function(context, args) {
12-
timeout = null;
13-
if (args) result = func.apply(context, args);
11+
var later = function() {
12+
var passed = now() - previous;
13+
if (wait > passed) {
14+
timeout = setTimeout(later, wait - passed);
15+
} else {
16+
timeout = null;
17+
if (!immediate) result = func.apply(context, args);
18+
// This check is needed because `func` can recursively invoke `debounced`.
19+
if (!timeout) args = context = null;
20+
}
1421
};
1522

16-
var debounced = restArguments(function(args) {
17-
if (timeout) clearTimeout(timeout);
18-
if (immediate) {
19-
var callNow = !timeout;
23+
var debounced = restArguments(function(_args) {
24+
context = this;
25+
args = _args;
26+
previous = now();
27+
if (!timeout) {
2028
timeout = setTimeout(later, wait);
21-
if (callNow) result = func.apply(this, args);
22-
} else {
23-
timeout = delay(later, wait, this, args);
29+
if (immediate) result = func.apply(context, args);
2430
}
25-
2631
return result;
2732
});
2833

2934
debounced.cancel = function() {
3035
clearTimeout(timeout);
31-
timeout = null;
36+
timeout = args = context = null;
3237
};
3338

3439
return debounced;

‎underscore-esm.js

+18-13
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎underscore-esm.js.map

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎underscore.js

+18-13
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎underscore.js.map

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
Please sign in to comment.