What are callback functions in JavaScript?


When a function is passed to another function, it is called a callback function. It goes over this function than to call a passed function.

Example

You can try to run the following code to learn how to work with callback functions −

<html>
   <head>
      <script>
         var callback = function(myCallback) {
            setTimeout(function() {
               myCallback();
            }, 5000);
         };
         
         document.write("First is displayed");
         document.write("<br>Second is displayed");
         
         callback(function() {
             document.write("This is Callback function");
         });
         document.write("<br>Last is displayed");
      </script>
   </head>
</html>

Updated on: 23-Jun-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements