jQuery in Action
Functions as first-class citizens
329
A.2.2 Functions as callbacks
Top-level functions are all well and good when our code follows a nice and
orderly synchronous flow, but the nature of
orderly synchronous flow, but the nature of
HTML
pages--once loaded--is far
from synchronous. Whether we are handling events, instituting timers, or making
Ajax requests, the nature of the code in a web page is asynchronous. And one of
the most prevalent concepts in asynchronous programming is the notion of a call-
back function.
Ajax requests, the nature of the code in a web page is asynchronous. And one of
the most prevalent concepts in asynchronous programming is the notion of a call-
back function.
Let's take the example of a timer. We can cause a timer to fire--let's say in five
seconds--by passing the appropriate duration value to the
window.setTimeout()
method. But how does that method let us know when the timer has expired so
that we can do whatever it is that we're waiting around for? It does so by invoking
a function that we supply.
that we can do whatever it is that we're waiting around for? It does so by invoking
a function that we supply.
Let's consider the following code:
function hello() { alert('Hi there!'); }
setTimeout(hello,5000);
We declare a function named
hello
and set a timer to fire in 5 seconds, expressed
as 5000 milliseconds by the second parameter. In the first parameter to the
set-
Timeout()
method, we pass a function reference. Passing a function as a parame-
ter is no different than passing any other value--just as we passed a
Number
in the
second parameter.
When the timer expires, the
hello
function is called. Because the
setTime-
out()
method makes a call back to a function in our own code, that function is
termed a callback function.
This code example would be considered nave by most advanced JavaScript cod-
ers because the creation of the
hello
name is unnecessary. Unless the function is to
be called elsewhere in the page, there's no need to create the
window
property
hello
to momentarily store the
Function
instance to pass it as the callback parameter.
The more elegant way to code this fragment is
setTimeout(function() { alert('Hi there!'); },5000);
in which we express the function literal directly in the parameter list, and no
needless name is generated. This is an idiom that we'll often see used in
jQuery code when there is no need for a function instance to be assigned to a
top-level property.
needless name is generated. This is an idiom that we'll often see used in
jQuery code when there is no need for a function instance to be assigned to a
top-level property.
The functions we've created in the examples so far are either top-level func-
tions (which we know are top-level
window
properties) or assigned to parameters