Skip to content

Instantly share code, notes, and snippets.

@anvk
Last active October 20, 2015 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anvk/a0ef25d5288d3272a19f to your computer and use it in GitHub Desktop.
Save anvk/a0ef25d5288d3272a19f to your computer and use it in GitHub Desktop.
Execute function N times per threshold
/*
* func - function to be called
* threshold - time period in milliseconds
* N - how many function calls will be allowed to execute
*/
var debounceN = function(func, threshold, N) {
var counter = 0;
return function f() {
if (counter >= N) {
return;
}
var obj = this, args = arguments, timeout;
function execute() {
counter -=1;
clearTimeout(timeout);
};
counter += 1;
timeout = setTimeout(execute, threshold || 100);
func.apply(obj, args);
};
};
// Example
// Ensure that only 5 functions could be executed every 10 seconds
var optimizedFunc = debounceN(function() {
// my complex logic here
}, 1000, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment