Rate-limiting JavaScript function calls
ryhan.org
ryhan.org
If polling is what's needed then it makes more sense to use setInterval and have a better guarantee of when things are being run. Or you could stuff events into a buffer and have a function consume them periodically - either way, when you lose an event it's either 1. irrelevant, because polling only cares about the state at time t and not the events, or 2. deterministic, because your consumer function decided to get rid of it.
Suppose the user is entering the word "hacker" at .101 seconds per character, and your cooldown time is .3, your code will do something like this:
t=0.000 : 'h' FIRE
t=0.101 : 'a'
t=0.202 : 'c'
t=0.303 : 'k' FIRE
t=0.404 : 'e'
t=0.505 : 'r'
If the expensive, rate-limited function is an AJAX call to the server to see if a username is available, for example, you'll want to call again with "hacker" at t=0.6 seconds, not keep displaying the result for "hack" forever.Actually, the expected behavior isn't sufficiently well-specified to determine whether the code implements it. But I believe many applications of such code will need to take care to avoid the behavior I describe.
As suggested in another comment, I'd use a setInterval (classic JS) or a separate thread (HTML5 or node.js) to periodically check if the function needs to be run, and if so, run it.
$(emailTextBoxId).keyup(function (event) {
//executes a function, once, after waiting a specified number of milliseconds
setTimeout("CheckEmailAddressAvailability()", 1300);
//stopping bubble
return false;
});$(emailTextBoxId).keydown(function (event) {
safeToPerformEmailCheck = true;
document.getElementById("ValidEmailAdd").style.display = "none";
document.getElementById("ExistingEmailAcc").style.display = "none";
//document.getElementById("InvalidEmailAdd").style.display = "none";
});$(emailTextBoxId).mouseup(function (event) {
safeToPerformEmailCheck = true;
CheckEmailAddressAvailability();
});Edit: I just saw the examples posted by fellow readers at following links are much better than mine. I am glad I really learned some good stuff today and I will edit my code today as first thing once I go home this eve. Really neat.
Other examples are things like memoizing/caching values, logging, etc.
http://closure-library.googlecode.com/svn-history/r44/docs/c...
Not that it's bad to know how to do it yourself, but I'd make sure my implementation was sound before sharing it as advice.
https://github.com/documentcloud/underscore/blob/master/unde...
I updated the post with a link to underscore's annotated source for debounce and throttle. Thanks for the tip.