Last active
October 5, 2015 21:57
-
-
Save fcarriedo/2883306 to your computer and use it in GitHub Desktop.
Throttle 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
/** | |
* Returns a functions that ensures that only one call | |
* executes every given milliseconds. | |
*/ | |
function throttle(funct, time) { | |
var active = false; | |
return function() { | |
if(!active) { | |
active = true; | |
funct.apply(this, arguments); | |
setTimeout(function() {active = false}, time); | |
} | |
}; | |
} | |
/** | |
* (comments from underscore.js) | |
* Creates and returns a new debounced version of the passed | |
* function which will postpone its execution until after wait | |
* milliseconds have elapsed since the last time it was invoked. | |
* Useful for implementing behavior that should only happen | |
* after the input has stopped arriving. | |
* For example: rendering a preview of a Markdown comment, | |
* recalculating a layout after the window has stopped being | |
* resized, and so on. | |
*/ | |
function debounce(funct, time) { | |
var active = false; | |
var ctx = this; // What context do we want it to have? | |
return function() { | |
if(!active) { | |
active = true; | |
setTimeout(function() { | |
funct.apply(ctx, arguments); | |
active = false; | |
}, time); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment