Skip to content

Instantly share code, notes, and snippets.

@fcarriedo
Last active October 5, 2015 21:57
Show Gist options
  • Save fcarriedo/2883306 to your computer and use it in GitHub Desktop.
Save fcarriedo/2883306 to your computer and use it in GitHub Desktop.
Throttle function
/**
* 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