Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Asynchronous

Asynchronous JavaScript

The examples in the previous chapter were simplified to focus on demonstrating the syntax of callback functions.

Example

function myDisplayer(something) {
  document.getElementById(“demo”).innerHTML = something;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(55, myDisplayer);

In the example above, myDisplayer is the name of a function that is passed as an argument to myCalculator().

In real-world scenarios, callbacks are commonly used with asynchronous functions. A typical example is JavaScript’s setTimeout() function.

Waiting for a Timeout

When using the JavaScript setTimeout() function, you can provide a callback function to be executed once the timeout period has elapsed.

Example

setTimeout(myFunction, 3000);

function myFunction() {
  document.getElementById(“demo”).innerHTML = “I love You !!”;
}

In the example above, myFunction is used as a callback and passed as an argument to setTimeout(). The value 3000 represents the number of milliseconds before the timeout, so myFunction() will be called after 3 seconds.

Instead of passing just the name of a function as an argument to another function, you can also pass the entire function itself.

Example

setTimeout(function() { myFunction(“I love You !!!”); }, 3000);

function myFunction(value) {
  document.getElementById(“demo”).innerHTML = value;
}

In the example above, function(){ myFunction(“I love You !!!”); } is used as a callback. It is a full function, which is passed to setTimeout() as an argument. The value 3000 represents the number of milliseconds before the timeout, so myFunction() will be called after 3 seconds.

Waiting for Intervals:

When using the JavaScript setInterval() function, you can specify a callback function to be executed at each interval.

Example

setInterval(myFunction, 1000);

function myFunction() {
  let d = new Date();
  document.getElementById(“demo”).innerHTML=
  d.getHours() + “:” +
  d.getMinutes() + “:” +
  d.getSeconds();
}

In the example above, myFunction is used as a callback and passed as an argument to setInterval(). The value 1000 represents the number of milliseconds between intervals, so myFunction() will be called every second.

Callback Alternatives

Asynchronous programming allows JavaScript programs to initiate long-running tasks while continuing to execute other tasks in parallel.

However, asynchronous code can be challenging to write and debug. For this reason, most modern asynchronous JavaScript methods no longer rely on callbacks. Instead, asynchronous programming is handled using Promises.

Note: You will learn about Promises in the next chapter of this tutorial.