Asynchronous JavaScript

"I will finish later!"

Functions that run in parallel with other functions are called asynchronous (asynchronous)

A good example is JavaScript setTimeout()

Asynchronous JavaScript

The examples used in the previous chapter have been greatly simplified.

The purpose is to demonstrate the syntax of callback functions:

Example

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}
myCalculator(5, 5, myDisplayer);

Try It Yourself

In the above example,myDisplayer is the name of the function.

It is passed as a parameter to myCalculator();.

In the real world, callbacks are most commonly used with asynchronous functions.

A typical example is JavaScript setTimeout();.

Waiting for timeout

When using JavaScript functions setTimeout(); You can specify the callback function to be executed after the timeout:

Example

setTimeout(myFunction, 3000);
function myFunction() {
  document.getElementById("demo").innerHTML = "I love You !!";
}

Try It Yourself

In the above example,myFunction It is used as a callback.

Function (function name) is passed as a parameter to setTimeout();.

3000 is the number of milliseconds before the timeout, so it will be called after 3 seconds myFunction();.

Remember not to use parentheses when passing a function as a parameter.

Correct: setTimeout(myFunction, 3000);

Error: setTimeout(myFunction(), 3000);

If you do not pass the function name as a parameter to another function, you can always pass the entire function:

Example

setTimeout(function() { myFunction("I love You !!!"); }, 3000);
function myFunction(value) {}}
  document.getElementById("demo").innerHTML = value;
}

Try It Yourself

In the above example,function() { myFunction("I love You !!!"); } used as a callback. It is a complete function. A complete function is passed as a parameter to setTimeout().

3000 is the number of milliseconds before the timeout, so it will be called after 3 seconds myFunction();.

Waiting interval:

When using JavaScript functions setInterval(); at the time, you can specify the 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();
}

Try It Yourself

In the above example,myFunction used as a callback.

Function (function name) is passed as a parameter to setInterval();.

1000 is the number of milliseconds between intervals, so myFunction(); call once per second.

Waiting for the file

If you create functions to load external resources (such as scripts or files), you cannot use these contents before they are fully loaded.

This is the best time to use callbacks.

This example loads an HTML file (mycar.html) and display the HTML file in the web page when it is fully loaded:

Waiting for the file:

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}
function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myCallback(this.responseText);
    }
      myCallback("Error: " + req.status);
    }
  }
  req.send();
}
getFile(myDisplayer);

Try It Yourself

In the above example,myDisplayer used as a callback.

Function (function name) is passed as a parameter to getFile().

The following is mycar.html Copy:

mycar.html

<img src="img_car.jpg" alt="Nice car" style="width:100%">
<p>A car is a wheeled, self-powered motor vehicle used for transportation.</p>
<p>Most definitions of the term specify that cars are designed to run primarily on roads, to have seating for one to eight people, and typically have four wheels.</p>
<p>(Wikipedia)</p>