You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello! Thanks for your nice and clean debounce function. Lodash's is powerful but overly complicated for most use. I optimized your code and also wrote it for ES6.
You only need timeout to be outside the returned closure. The rest of the vars can go inside.
You can use Date.now() instead of new Date().
You don't need to save the context for the func.apply(), you can just pass null.
You can use a ternary to return an IIFE which returns nothing to set the timeout variable to undefined.
ES5
var debounce = function(wait, func) {
var timeout;
return function() {
var last,
args = [].slice.call(arguments, 0),
timestamp = Date.now(),
later = function() {
last = Date.now() - timestamp,
timeout = wait > last ? setTimeout(later, wait - last) : function() { func.apply(null, args); }();
};
timeout || (timeout = setTimeout(later, wait));
}
};
In ES6, you can use the ...args operator instead of [].slice.call().
const debounce = (wait, func) => {
var timeout;
return (...args) => {
var last,
timestamp = Date.now(),
later = () => {
last = Date.now() - timestamp;
timeout = wait > last ? setTimeout(later, wait - last) : (() => { func.apply(null, args); })();
};
timeout || (timeout = setTimeout(later, wait));
}
};
The text was updated successfully, but these errors were encountered:
Hello! Thanks for your nice and clean debounce function. Lodash's is powerful but overly complicated for most use. I optimized your code and also wrote it for ES6.
ES5
In ES6, you can use the ...args operator instead of [].slice.call().
The text was updated successfully, but these errors were encountered: