Asynchronous programming is a technique that allows our program to move on to other tasks without having to wait for a previous task to finish. The program can start a task and then continue to respond to other events while it runs.
We can visualize this with the help of a real-world scenario. In the current ecosystem of cloud technologies, programs are constantly communicating with remote servers, which can prove to be time-consuming when dealing with huge files. If we use asynchronous programming techniques in our program, we can cut down the execution time of tasks that might become unresponsive or pause while waiting for another task to complete.
Before we dive deeper into asynchronous programming in JavaScript, it`s crucial to learn about event loop mechanism.
In easy terms, an event loop is a mechanism that lets JavaScript address asynchronous code by constantly tracking the execution stack and the task queue. The execution stack is where synchronous code is executed, whereas the task queue is where asynchronous code is queued for execution.
The event loop examines the task queue for any pending tasks whenever the execution stack is empty. If there are any jobs in the queue, the event loop sends them synchronously into the execution stack.
This process continues indefinitely, with the event loop continuously monitoring the execution stack and the task queue, ensuring that JavaScript can handle both synchronous and asynchronous code.
Callback functions are one of the most common ways to write asynchronous code in JavaScript. A callback function is a function that is passed as an argument to another function and is called when that function has completed its task.
Let’s look at a very simple example of adding numbers, with and without the use of callbacks:
// Define a function called add that takes three parameters: a, b, and cfunction add(a, b, c) {// Create a new variable called result that is the sum of a, b, and clet result = a + b + c;// Return the result of the additionreturn result;}// Call the add function with the values 15, 4, and 23, and store the result in a variable called sumlet sum = add(15, 4, 23);// Log the value of the sum variable to the consoleconsole.log(sum);
Note: Do not use parenthesis when passing a function as an argument.
This example covered a straightforward function and got us up to speed with the syntax of how JavaScript uses callbacks.
Asynchronous functions, in which one function must wait for another function, are where callbacks are fully utilized and we will take a look at them next.
setTimeout
functionWe can define a callback function to be executed on a time-out when using the JavaScript setTimeout()
method.
Let’s take a look at how we use this asynchronous function with the help of an example.
// This code uses the setTimeout() method to schedule the execution of the 'myFunction()' function after a delay of 3000 milliseconds (3 seconds).setTimeout(myFunction, 3000);// This is the 'myFunction()' function that will be executed after the delay.// It logs the string "Hello World" to the console.function myFunction() {console.log("Hello World");}
The above code sets a timeout of 3 seconds using the setTimeout()
function. The setTimeout()
function takes two arguments:
The function to be executed after the specified delay
The second argument is the delay in milliseconds
setInterval
functionAnother important asynchronous function available to us in JavaScript is the setInterval
function. We can specify a callback function to be executed for the specified interval.
Let’s take a look at an example to understand it better.
let counter = 0;// This will execute the function every 2 secondslet intervalId = setInterval(function() {counter++;console.log("Counter value: " + counter);}, 2000);// This will stop the interval after 10 secondssetTimeout(function() {clearInterval(intervalId);console.log("Interval stopped.");}, 11000);
This code declares a variable called counter
, uses setInterval()
to execute an anonymous function that increments the counter
and logs its value to the console every 2000
millisecond (2 seconds). The interval ID returned by setInterval()
is stored in the intervalId
variable, which is later used to stop the interval after 11000
milliseconds (11 seconds) using clearInterval()
.
The setTimeout()
function is used to call clearInterval()
after 11 seconds, which will log "Interval stopped."
to the console.
JavaScript provides several ways to write asynchronous code, including callbacks, promises, and async/await. The key to mastering asynchronous programming is understanding the event loop and how it manages the execution of the asynchronous code.
Free Resources