Introduction to asynchronous calls in JavaScript

Introduction to asynchronous programming

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.

Introduction to the event loop mechanism

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.

Callbacks in JavaScript

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:

Example

// Define a function called add that takes three parameters: a, b, and c
function add(a, b, c) {
// Create a new variable called result that is the sum of a, b, and c
let result = a + b + c;
// Return the result of the addition
return result;
}
// Call the add function with the values 15, 4, and 23, and store the result in a variable called sum
let sum = add(15, 4, 23);
// Log the value of the sum variable to the console
console.log(sum);
Adding numbers without callback

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.

Asynchronous functions in JavaScript

The setTimeout function

We 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.

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");
}
An example of the setTimeout function

Explanation

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

The setInterval function

Another 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 seconds
let intervalId = setInterval(function() {
counter++;
console.log("Counter value: " + counter);
}, 2000);
// This will stop the interval after 10 seconds
setTimeout(function() {
clearInterval(intervalId);
console.log("Interval stopped.");
}, 11000);
An example of the setInterval function

Explanation

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.

Conclusion

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

Copyright ©2024 Educative, Inc. All rights reserved