Skip to content

Commit

Permalink
Merge pull request #2892 from kritollm/master
Browse files Browse the repository at this point in the history
Reimplementing timer optimization  #1269
  • Loading branch information
jgonggrijp committed Dec 7, 2020
2 parents d10beb9 + 6568211 commit 311b04e
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 42 deletions.
33 changes: 19 additions & 14 deletions modules/debounce.js
@@ -1,34 +1,39 @@
import restArguments from './restArguments.js';
import delay from './delay.js';
import now from './now.js';

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

var later = function(context, args) {
timeout = null;
if (args) result = func.apply(context, args);
var later = function() {
var passed = now() - previous;
if (wait > passed) {
timeout = setTimeout(later, wait - passed);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
// This check is needed because `func` can recursively invoke `debounced`.
if (!timeout) args = context = null;
}
};

var debounced = restArguments(function(args) {
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
var debounced = restArguments(function(_args) {
context = this;
args = _args;
previous = now();
if (!timeout) {
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(this, args);
} else {
timeout = delay(later, wait, this, args);
if (immediate) result = func.apply(context, args);
}

return result;
});

debounced.cancel = function() {
clearTimeout(timeout);
timeout = null;
timeout = args = context = null;
};

return debounced;
Expand Down
31 changes: 18 additions & 13 deletions underscore-esm.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion underscore-esm.js.map

Large diffs are not rendered by default.

31 changes: 18 additions & 13 deletions underscore.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion underscore.js.map

Large diffs are not rendered by default.

0 comments on commit 311b04e

Please sign in to comment.