Asynchronous JavaScript


"I'll complete it later!"

Functions that run parallel with other functions are referred to as asynchronous

A clear instance is the use of JavaScript setTimeout().

Asynchronous JavaScript

The instances mentioned in the last section were quite straightforward.

The examples were meant to show how callback functions are written in code.

In the given example, the function is named myDisplayer.

It gets sent to the function myCalculator() as input.

In everyday situations, callbacks are commonly paired with asynchronous functions.

An example of this is the JavaScript function called setTimeout().


Waiting for a Timeout

When you use the JavaScript function setTimeout(), you can define a callback function to run when the timeout occurs:

In the example provided, the function called myFunction is utilized as a callback.

The function called myFunction is given as an argument to the setTimeout()function.

The function myFunction() will be triggered after 3 seconds because the time-out is set to 3000 milliseconds.

Note

When you provide a function as an argument, avoid using parentheses.

Correct: Set a timer to execute "myFunction" after a delay of 3000 milliseconds.

Incorrect: setTimeout(myFunction(), 3000);

Instead of giving the name of a function as input to another function, you can simply provide the entire function itself.

In the example below, the code function(){ myFunction("I love You !!!"); } serves as a callback. This code represents a whole function, and it is given as an argument to the setTimeout() function.

The timeout duration is 3000 milliseconds, meaning that the function myFunction() will be executed after 3 seconds.


Waiting for Intervals:

When you employ the JavaScript function setInterval(), you have the option to define a callback function that will run at regular intervals:

In the given example, the function called myFunction is used as a callback.

The function called myFunction is given as an argument to the setInterval()function.

The interval between calls to myFunction() is 1000 milliseconds, meaning it will be executed every second.


Callback Alternatives

Using asynchronous programming in JavaScript allows programs to begin tasks that take a long time to complete and simultaneously carry out other tasks in parallel.

However, writing and debugging asynchronous programs can be challenging.

Due to this, many contemporary JavaScript techniques for handling asynchronous tasks avoid using callbacks. Instead, in JavaScript, the solution to asynchronous programming lies in utilizing Promises.

Note

In the upcoming tutorial chapter, you'll discover more about promises.