Delayed Call in Javascript

In the javascript world, user is best described as a source of random and contradictory signals. He starts one action, then another, then third (that cancels previous both).

Most widespread real-world example is autocomplete: we have to make requests based on user input, but each consequent keypress requires different request than one that is being currently done (or recently been).

To make things clear, let’s call user’s action that requires some processing a command and actions that the script should perform and that take some time a request.

There are several possible strategies when dealing with stream of user commands:

  • A. – Most simple solution – each command generates a request and each consequent response replaces former response. This is not too good because of possible (and in most cases inevitable) race conditions: sometimes response for latter request can come first. Also it’s quite bad for the server since it has to respond many times while only one response will be really needed.
  • B. – Each command generates a request and cancels former request. More difficult to implement; much better for the user since he won’t get outdated results because of the race condition. But still bad for the server since he gets too much requests (and many of them are cancelled in the middle). [remark: that's how it been done in YUI AutoComplete before 2.8.0]
  • C. – each command starts a timer and cancels previous timer; if no command received for some time, request is made (and former request is cancelled). This is most difficult to implement since it’s case B plus a timer. You can think that it’s worse for the user since he has to wait a little while typing something in to get a results, but in most cases it’s better, since system won’t be busy with current requests and it will be able to serve really necessary request quickier. Also it’s much much better for the server since it will be less likely over-abused by excessive requests. [that was implemented in YUI AutoComplete since 2.8.0]

Timeout that calls a request and that is reset with each command is quite common practice in Javascript. To simplify implementation of this pattern I have
developed Javascript Delayed Call class (it’s called Ae_Delayed_Call).

Get to know with this theme closely in our programmer's blog: Delayed Call in Javascript