DEV Community

Kevin O'Shaughnessy
Kevin O'Shaughnessy

Posted on

Asynchronous JavaScript

When learning the basics of JavaScript, you should quickly understand that it is a single-threaded language. This means that only one line of code can run at once. In order to run complex code, it is necessary to understand how to run code beyond the basic sequential flow.

Asynchronous JavaScript is particularly useful when dealing with code which may take longer to run. MDN Web Docs defines it as:

"Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result."

Examples of where this can be useful include callback functions, fetching data from an API, promises, and events with event listeners.

If we look at an example, we can see how this works. The following, setTimeout() is a method that sets a timer for a specified piece of code. Notice that the number of seconds, rather than the order, dictate what the output will be.

setTimeout(() => {
console.log("message 1");
}, 7000);
setTimeout(() => {
console.log("message 2");
}, 5000);
setTimeout(() => {
console.log("message 3");
}, 1000);

// Output:

// message 3
// message 2
// message 1

Message 3 only takes 1 second, message 2 5 seconds, and message 1 7 seconds. The code is read in order, line by line, but the output is asynchronous, based on the time it takes to process the three different messages.

Asynchronous operations are handled by an event loop. The code in the console will be read and invoked line by line but certain operations in the stack will take more time and be placed in a task queue, from which the event loop will manage their execution in a single-threaded language like JavaScript.

Top comments (0)