Re:Rate-limiting JavaScript function calls
by csense on Monday October 15, 2012 @05:01PM
(#4657149)
This program has a bug.
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.
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:
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.