JavaScript Callback Functions

In JavaScript, functions are of type objects. A callback function is a piece of executable code that is passed as an argument to other function. jQuery heavily depends on callback functions

<!DOCTYPE html>
<html>
<body>

<p id="demo">Callback function example</p>

<script>
function showMessage(message){
  setTimeout(function(){
    alert(message);
  }, 3000);  
}

showMessage('Function called 3 seconds ago');
</script>

</body>
</html>

Download the code Run the code

JavaScript is executed line by line. It cannot wait for another function to complete its process before executing next function in line. So a callback function is called after some specific event is completed.

For example, execute a specific sequence of code after an Ajax request is completed based on output of a server call. So in this case a callback function is passed to as an argument and it will get called after completion of a request.

jQuery $.ajax uses callback functions to process output.

 $.ajax({
      url: "demo_ajax_load.txt", 
      async: false, 
      success: function(result){
          $("div").html(result);
      }
});
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .