Asynchronous Programming
Asynchronous programming is a technique that allows you to execute a resource-intensive task in a non-blocking way.
In the context of the earlier example, while a "long task" is running, the "control" is returned to the application (e.g., the browser), so it can continue to handle user input and perform other tasks.
JavaScript itself does not support async programming! However, with the help of its execution environment (e.g., the browser), it can behave asynchronously. In particular, operations like making a network request or querying a database can be (and almost always are) done asynchronously.
Here is our earlier example where I have used the built-in function setTimeout
to simulate a time-consuming task that runs asynchronously.
function task(id) { console.log("Task " + id); } function longtask(id) { console.log("Task " + id + " started!"); setTimeout(() => console.log("Task " + id + " finished!"), 5000); } task(1); longtask(2); task(3); task(4);
The
setTimeout
is an example of an asynchronous or non-blocking function.
A helpful way to think about setTimeout
is to schedule a task to be performed in the future. It, however, does not wait until the task is done. Therefore, setTimeout
does not block the execution of other functions. Task-3, for instance, does not need to wait for 5 seconds to get its chance to be executed.
Aside: the setTimeout
is not built into JavaScript! However, it is part of the Web API that is made available to JavaScript in the browser. Perhaps more concretely, you could access it as window.setTimeout
. In NodeJS applications, setTimeout
is made available as part of the global
object.
Resources
- YouTube video Asynchronous vs. Synchronous Programming by Web Dev Simplified.
- Article JavaScript Timers: Everything you need to know published on freeCodeCamp.