Java Reference
In-Depth Information
We covered callbacks way back in Chapter 4 . You'll recall that they're functions that are
passed to other functions as arguments.
Event-driven Asynchronous Programming
Callbacks facilitate event-driven asynchronous programming. JavaScript is a single-
threaded environment , which means that only one piece of code will ever be processed at
a time. This may seem like a limitation, but non-blocking techniques can be used to ensure
that the program continues to run. Instead of waiting for a event to occur, a callback can be
created that's invoked when the event happens. This means that the code is able to run out of
order, or asynchronously . Events can be DOM events, such as the click and keyPress
that we looked at in Chapter 7 , but they can also be events such as waiting for a file to load,
waiting for data from a database or other website, or waiting for the program to complete
a complex operation. By using callbacks, we ensure that these events don't hold up the ex-
ecution of other parts of the program. Once the event occurs, the callback will be invoked
before returning to the rest of the program.
Here's an example of a function called wait() that accepts a callback. To simulate an op-
eration that takes some time to happen, we can use the setTimeout() function to call the
callback after a given number of seconds:
function wait(message, callback, seconds){
setTimeout(callback,seconds * 1000);
Now let's create a callback function to use:
function selfDestruct(){
If we invoke the wait() function and then log a message to the console, we can see how
JavaScript works asynchronously:
Search WWH ::

Custom Search