What Are Asynchronous Methods in JavaScript?
In JavaScript, your code is like an assembly line. JavaScript is single-threaded, so it processes one task after the other. Productivity comes to a halt if a single task takes a long time or if we need to request information from an external service.
Luckily we can keep our assembly line moving by using certain APIs on the server or browser to delegate instructions so they can processed asynchronously. Our instructions take the form of callback functions which are diverted to a separate queue, which is monitored by an event loop.
Utilizing asynchronous methods, our assembly line continues to function without interruption. The event loop presents the completed work to us when our assembly line is ready to receive it, and we optimize delivery of results.
Time Consuming Processes
For demonstration purposes, let’s create a function that takes some time to complete.
function countToLargeNumber(largeNumber) {
let count = 0;
while (count < largeNumber) {
count++; // Counting to a large number
}
console.log("Finished counting to " + largeNumber);
}
console.log("Starting count...");
countToLargeNumber(1e9);
console.log("Blocked");
Here is the Console output in Chrome:
Starting count...
Finished counting to 1000000000
Blocked
While JavaScript was busy counting, it was unable to do anything else. It wouldn’t be able to update a UI element, for example.
Unblocking the Main Thread
One way to unblock the main thread is to wrap blocking synchronous code in an asynchronous method like setTimeout(). This works even with a timeout of 0:
function countToLargeNumber(largeNumber) {
return setTimeout(() => {
let count = 0;
while (count < largeNumber) {
count++; // Counting to a large number
}
console.log("Finished counting to " + largeNumber);
}, 0)
}
console.log("Starting count...");
countToLargeNumber(1e9);
console.log("Not blocked");
Here is the Console output in Chrome:
Starting count...
Not blocked
Finished counting to 1000000000
setTimeout() gave us the advantage of asynchronous execution so JavaScript can freely update our UI while the count to one billion is processed. This unblocked our main thread, but it doesn’t give us a way to handle errors. For that we have Promises.
Here are several asynchronous methods available in Javascript. Learn how to use them inside Promises:
- setTimeout() - execute a function after X milliseconds delay.
- setInterval() - execute a function every X milliseconds.
- requestAnimationFrame() - execute an animation function before the next repaint.
- XMLHttpRequest or fetch() - retrieve data from a file or URL.
Related posts:
Helpful references:
Have feedback on this topic?