26 May 2010

Concurrency, Javascript and JQuery

In any block of code, execution is sequential. Each line of code will not execute until the previous line has executed. If a line contains a function call, then the next line will begin execution after that function returns a value. If the function continues to execute code even after it returns a value, then the code in the original block is no longer executing sequentially, in other words two different blocks of code are running concurrently. Concurrency is generally achieved in software by some implementation of threads.

Asynchronous Javascript

In the context of a javascript web application, events such as making remote requests and receiving keyboard input occur asynchronously. For example, a user might make a keystroke while a remote request is still executing.

Since javascript in a web browser executes in a single thread, asynchronous events are handled by a queue. Events are handled sequentially, but if an event (such as receiving a response to a remote request) is not completed, then the associated code can be returned to the back of the queue and the next event can be handled. This gives an impression of concurrency to the user.

The functions that make asynchronous javascript in the browser possible are setTimeout(), setInterval() and clearInterval(). Libraries like JQuery make extensive use of them.


A callback is code which is passed as an argument. Javascript accepts callbacks, and both setTimeout() and setInterval() can take functions (i.e. code) as their first argument. JQuery uses callbacks in order to implement arbitrary event-handling code.

The $(document).ready() function in JQuery takes a callback, but only after an application page and its associated DOM has loaded.

$(document).ready() can also be written as JQuery() or just $().

d. sofer