Skip to content

Instantly share code, notes, and snippets.

@nik-kor
Created March 16, 2014 19:46
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 nik-kor/9588790 to your computer and use it in GitHub Desktop.
Save nik-kor/9588790 to your computer and use it in GitHub Desktop.
var funcCalls = {
/**
* Hash - func-name => last-called-timestamp
*/
timestamp: {},
/**
* Hash func-name => calls count
*/
count: {},
update: function() {}
};
/**
* @param {String} - f - Function.toString result
* @return {String}
*/
var getFuncName = function(f) {
//not implemented
};
var callsManager = {
MS_LIMIT: 1000,
CALLS_LIMIT: 5,
callFunc: function(func, context, args) {
var funcName = getFuncName(func),
calledMSAgo = (Date.now() - funcCalls.timestamp[funcName]);
if(funcName in funcCalls.timestamp
&& calledMSAgo < this.MS_LIMIT
&& funcCalls.count[funcName] >= this.CALLS_LIMIT
) {
setTimeout(function() {
func.apply(context, args);
funcCalls.update(funcName, Date.now());
}, this.MS_LIMIT - calledMSAgo);
return;
}
funcCalls.update(funcName, Date.now());
func.apply(context, args);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment