Last active
August 29, 2015 14:12
-
-
Save drifterz28/cb84f9e428b5d688b7ea to your computer and use it in GitHub Desktop.
Throttle and debounce from underscore.js
This file contains hidden or 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
/** | |
* @func function, a function to fire | |
* @wait int, wait time | |
* immediate bool, call function first then set timer | |
*/ | |
function debounce(func, wait, immediate) { | |
var timeout; | |
return function() { | |
var context = this, args = arguments; | |
var later = function() { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
var callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
} | |
/** | |
* @func function, a function to fire | |
* @wait int, wait time | |
* immediate obj, {leading: true, trailing: false} set function to fire first and/or last | |
*/ | |
function throttle(func, wait, options) { | |
var context, args, result; | |
var timeout = null; | |
var previous = 0; | |
if (!options) options = {}; | |
var later = function() { | |
previous = options.leading === false ? 0 : new Date().getTime(); | |
timeout = null; | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
}; | |
return function() { | |
var now = new Date().getTime(); | |
if (!previous && options.leading === false) previous = now; | |
var remaining = wait - (now - previous); | |
context = this; | |
args = arguments; | |
if (remaining <= 0 || remaining > wait) { | |
clearTimeout(timeout); | |
timeout = null; | |
previous = now; | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
} else if (!timeout && options.trailing !== false) { | |
timeout = setTimeout(later, remaining); | |
} | |
return result; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment