Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active April 25, 2018 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinweber/86532b4a7f01212b65e60b3faf051550 to your computer and use it in GitHub Desktop.
Save kevinweber/86532b4a7f01212b65e60b3faf051550 to your computer and use it in GitHub Desktop.
Debounce function
/**
* Debounce function
* based on https://davidwalsh.name/essential-javascript-functions
*/
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments,
later,
callNow;
later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
// Use it like this ...
var debouncedUpdate;
debouncedUpdate = debounce(function (value) {
myHandleChangeFunction(value);
}, 50);
$myInputFormField.on('input change keyup', function () {
debouncedUpdate(this.value);
});
/**
* Debounce function v2
* based on https://davidwalsh.name/essential-javascript-functions
* with leading/trailing support as seen on https://lodash.com/docs/4.17.10#debounce
*/
function debounce(func, wait, options) {
var timeout;
var debounceCount = 0;
options = options || {};
options.leading = options.leading || false;
options.trailing = options.trailing || true;
return function () {
var context = this,
args = arguments,
later,
callNow;
debounceCount += 1;
later = function () {
timeout = null;
// If leadEqualsTrail === 1 the debounce function was only triggered once
var leadEqualsTrail = debounceCount === 1;
if ((options.leading && !leadEqualsTrail) && options.trailing) {
func.apply(context, args);
}
debounceCount = 0;
};
callNow = options.leading && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
// Use it like this ...
var debouncedUpdate;
debouncedUpdate = debounce(function (value) {
myHandleChangeFunction(value);
}, 500, { leading: true, trailing: true });
$myInputFormField.on('input change keyup', function () {
debouncedUpdate(this.value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment