Last active
April 25, 2018 01:05
-
-
Save kevinweber/86532b4a7f01212b65e60b3faf051550 to your computer and use it in GitHub Desktop.
Debounce function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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