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 supports async programming! 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 that it schedules a task to be performed in the future. It, however, does not wait until the task is executed. 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.

I recommend viewing the short YouTube video Asynchronous Vs Synchronous Programming by Web Dev Simplified.