Skip to content

Instantly share code, notes, and snippets.

@TanAlex
Last active June 9, 2019 04:54
Show Gist options
  • Save TanAlex/075cd0df66ab6d4949803165cafbd18b to your computer and use it in GitHub Desktop.
Save TanAlex/075cd0df66ab6d4949803165cafbd18b to your computer and use it in GitHub Desktop.
[Javascript Utils]Javascript Utilities #utils
// Credit David Walsh (https://davidwalsh.name/javascript-debounce-function)
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
var called = false;
// This is the function that is actually executed when
// the DOM event is triggered.
return function executedFunction() {
// Store the context of this and any
// parameters passed to executedFunction
var context = this;
var args = arguments;
// The function to be called after
// the debounce time has elapsed
var later = function() {
// null timeout to indicate the debounce ended
timeout = null;
// Call function now if you did not on the leading end
if (!called) func.apply(context, args);
called = false;
};
// Determine if you should call the function
// on the leading or trail end
var callNow = immediate && !timeout;
if (callNow) {
func.apply(context, args);
called = true;
} else {
called = false;
}
// This will reset the waiting every function execution.
// This is the step that prevents the function from
// being executed because it will never reach the
// inside of the previous setTimeout
clearTimeout(timeout);
// Restart the debounce waiting period.
// setTimeout returns a truthy value (it differs in web vs node)
timeout = setTimeout(later, wait);
console.log(timeout);
// Call immediately if you're dong a leading
// end execution
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment