Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active March 14, 2017 05:53
Show Gist options
  • Save kavitshah8/7bf22bd1e8d934ba88ad to your computer and use it in GitHub Desktop.
Save kavitshah8/7bf22bd1e8d934ba88ad to your computer and use it in GitHub Desktop.
Debounce
// 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.
function debounce (cb, wait) {
var timeoutID
return function () {
clearTimeout(timeoutID)
timeoutID = setTimeout(cb, wait)
}
}
// If `immediate` is passed, trigger the function on the leading edge, instead of the trailing.
function debounce (cb, wait, immediate) {
var timeoutID
return function () {
function later () {
timeoutID = null
if (!timeoutID) {
cb()
}
}
var callNow = immediate && !timeoutID
clearTimeout(timeoutID)
timeoutID = setTimeout(later, wait)
if (callNow) {
cb()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment