Created
December 14, 2014 03:46
-
-
Save gosukiwi/ba0eb9bce58abc49a5b5 to your computer and use it in GitHub Desktop.
Backbone's debounce
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
var debounce = function(func, wait, immediate) { | |
var timeout, args, context, timestamp, result; | |
var now = Date.now || function() { | |
return new Date().getTime(); | |
}; | |
var later = function() { | |
var last = now() - timestamp; | |
if (last < wait && last >= 0) { | |
timeout = setTimeout(later, wait - last); | |
} else { | |
timeout = null; | |
if (!immediate) { | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
} | |
} | |
}; | |
return function() { | |
context = this; | |
args = arguments; | |
timestamp = now(); | |
var callNow = immediate && !timeout; | |
if (!timeout) timeout = setTimeout(later, wait); | |
if (callNow) { | |
result = func.apply(context, args); | |
context = args = null; | |
} | |
return result; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment