Timing and Asynchronous Techniques
Learn about timing functions, asynchronous programming, intervals, and how to implement a stopwatch.
We'll cover the following...
Timing functions
JavaScript provides a couple of useful methods that enable us to schedule when a function is called or to call a function at regular intervals. These can be useful for causing a delay before something happens, or displaying a timer on the screen.
The setTimeout
method
The setTimeout()
method accepts a callback function as its first parameter and a number of milliseconds as its second parameter. The callback function that’s provided as the first argument will be called after the time given as the second argument.
To see this in action, try running the following code. It should show an alert box after seven seconds. This is because the first argument is an anonymous arrow function that displays the alert box, and the second argument is
Notice that the method returns an integer. This is an ID used to reference that particular timeout.
Instead of trying to remember the value that’s returned when the timeout is set, it’s easier to assign a variable to the return value, like in the code example below:
We can use this variable to cancel the timeout using the clearTimeout()
method:
Asynchronous programming
A synchronous program is one that processes each line of code in the order it appears. The problem with this approach is that, if a particular part of the program takes a long time to complete, it will hold up the rest of the program. This means that time-consuming events such as the completion of a file download, getting data from a database, or loading a game will block anything else from happening.
One solution is to start a new thread to run different parts of the program. This means that if a process is taking a long time in one thread, other threads can be used for other tasks. The problem with multi-threaded programs is that it can be difficult to keep track of what’s happening in each thread, especially if the results of one thread are needed in another.
Another solution is to write asynchronous code, which runs out of order, or asynchronously. Instead of waiting for an operation to finish, a callback (or promise) is created, and the rest of the program continues to run. This ensures that waiting for a process to complete doesn’t hold up the execution of other parts of the program. Once the task is complete, the promise is said to be resolved and the callback returns the result back to the program.
The diagram below shows how a long process blocks the rest of the code from ...