Last active
October 20, 2015 13:21
-
-
Save anvk/a0ef25d5288d3272a19f to your computer and use it in GitHub Desktop.
Execute function N times per threshold
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
/* | |
* 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