By default, a JavaScript program is executed synchronously, meaning it will wait for the previous line to finish before moving on to the next. For example,
1function task1() {
2 console.log("Task 1 finished.");
3}
4
5function task2() {
6 console.log("Task 2 finished.");
7}
8
9function task3() {
10 console.log("Task 3 finished.");
11}
12
13task1();
14task2();
15task3();
1Task 1 finished.
2Task 2 finished.
3Task 3 finished.
The three tasks will be executed according to the sequence they are called.
However, imagine task number 2 is something that requires a long time. For demonstration purposes, we are using a for
loop to count to 9,000,000,000
, which should take a few seconds on your computer.
1function task1() {
2 console.log("Task 1 finished.");
3}
4
5function task2() {
6 for (let i = 0; i < 9000000000; i++) {} // This loop should take a few seconds to finish
7 console.log("Task 2 finished.");
8}
9
10function task3() {
11 console.log("Task 3 finished.");
12}
13
14task1();
15task2();
16task3();
Run this example code and notice that the tasks are still being executed based on the order in which they are called. This means task2()
will be blocking the execution of task3()
. But from our example, you can see that task3()
does not depend on task2()
, so this way of doing things is not very effective.
Instead, what if you could allow multiple tasks to run in parallel? For example, maybe in this case, you could enable task3()
to execute while waiting for task2()
.
Asynchronous programming
This is the concept of asynchronous programming. It is a programming technique that allows you to start a time-consuming task in parallel with other easier tasks, so that your program is still responsive.