w1coding.comAll tutorials

JavaScript Callbacks

JavaScript lessons
  1. Environment Setup
  2. Introduction
  3. Enviroment
  4. Basics
  5. Variables
  6. Operators
  7. Condition
  8. Functions
  9. Arrays
  10. Bjects
  11. DOM
  12. Objects
  13. Colors
  14. DOM
  15. Events
  16. Validation
  17. JSON
  18. Error
  19. Callbacks
  20. Promises
  21. Fetch
  22. Local
  23. Modules
  24. Animation
  25. Classes
  26. Iframes
  27. Responsive

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.