Skip to content

Commit

Permalink
fix(utils): fix debounce function
Browse files Browse the repository at this point in the history
  • Loading branch information
matmkian committed Sep 5, 2019
1 parent 6cd1fc6 commit 96c62f7
Showing 1 changed file with 37 additions and 13 deletions.
50 changes: 37 additions & 13 deletions core/js/utils/utils_service.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,57 @@ function UtilsService($rootScope) {
* @return {Function} The debounced function.
*/
function debounce(func, wait, immediate) {
let timeout;
let args, context, result, timeout, timestamp;

return () => {
// eslint-disable-next-line import/unambiguous, consistent-this
const context = this;
wait = wait || 500;

// eslint-disable-next-line prefer-rest-params
const args = arguments;
const later = () => {
const last = Date.now() - timestamp;

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

if (!immediate) {
func.apply(context, args);
result = func.apply(context, args);

if (!timeout) {
// eslint-disable-next-line no-multi-assign
context = args = null;
}
}
};
}
};

const callNow = immediate && !timeout;
const debounced = () => {
context = this;
// eslint-disable-next-line prefer-rest-params
args = arguments;
timestamp = Date.now();

clearTimeout(timeout);
const callNow = immediate && !timeout;

timeout = setTimeout(later, wait);
if (!timeout) {
timeout = setTimeout(later, wait);
}

if (callNow) {
func.apply(context, args);
result = func.apply(context, args);
// eslint-disable-next-line no-multi-assign
context = args = null;
}

return result;
};

debounced.clear = () => {
clearTimeout(timeout);
// eslint-disable-next-line no-multi-assign
timeout = context = args = null;
};

return debounced;
}

/**
Expand Down

0 comments on commit 96c62f7

Please sign in to comment.