callbacks

Asynchronous JavaScript - Callbacks

Asynchronous JavaScript - Callbacks

Asynchronous JavaScript allows tasks to run in the background, so the web page remains responsive.

What is a Callback?

A callback is a function passed into another function as an argument, which is executed once the task is completed:

      
        function fetchData(callback) {
          setTimeout(function() {
            console.log("Data fetched");
            callback();
          }, 2000);
        }

        function displayData() {
          console.log("Displaying data");
        }

        fetchData(displayData);
      
    

Activity

Try It Yourself!

Create a function that simulates a delay and then calls another function to display a message after 3 seconds.

Quiz

Quick Quiz

  1. What is a callback in JavaScript?
  2. What does setTimeout do?
  3. Why is asynchronous JavaScript useful?

Answers: A function passed as an argument; delays execution of code; keeps the webpage responsive.