Callback Functions are functions that are passed as arguments to other function.

- Example (see the comments in code):
<script type="text/javascript">
// defines a callback function
function callback(x) {
  return 2*x;
}

// defines a function that will use the callback() as argument
// param will represent the result returned by callback function passed as argument
function test(param) {
  alert(param);
}

// calls the test() function with callback() as argument
test( callback(8) );      // outputs 16
</script>
• There are JavaScript functions that can be used only with callback function. For example: setTimeout() and setInterval().
Example, displays the number of seconds into a HTML element. Test yourself this example.
<div id="show_s"></div>
<script type="text/javascript">
var seconds = 0;
// used as callback function in setInterval()
function addSeconds(x) {
  // increments the seconds and adds the value in html tag with id="show_s"
  seconds++;
  document.getElementById('show_s').innerHTML = seconds;
}

// calls the addSeconds() to every second (1000 milliseconds)
setInterval('addSeconds()', 1000);
</script>
• Anonymous functions can also be used as callback functions.
- Here is an exaple with setTimeout() and an anonymous function used as argument.
<script type="text/javascript">
// displays an alert window after 2 seconds
setTimeout(function(){
  alert('http://CoursesWeb.net/');
}, 2000);
</script>
The callback function can be very useful when we want to finish a long task, while allowing us to continue the execution of the JavaScript code.
- A good example is with an Ajax function that receives a callback function as argument. When the server response is completely received, it is passed to the callback function, but in the meen time the script continues to preccess the other instructions.
- If you want to test this example, you have to create a text file, named "test.txt", with some text, in the same folder in which you have the page with this script.
<script type="text/javascript">
// gets data from external file
// receives the URL address of the file, and a callback function that will be called when the response is received
function ajaxF(url, callback) {
  var request =  (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");      // sets the XMLHttpRequest instance

  request.open("GET", url);			// define the request
  request.send(null);	   	// sends data

  // Check request status,  when the response is completely received pass it to callback function
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      callback(request.responseText);
    }
  }
}

// the callback function
function addResp(resp) {
  alert(resp);
}

// calls the ajaxF() function, passing the file address, and the callback function
ajaxF('test.txt', addResp);

// continue the script while the Ajax and callback functions are executed
alert('Message 1');
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="http://coursesweb.net/" title="CoursesWeb.net">CoursesWeb.net</a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
  font-family:"Calibri",sans-serif;
}
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
alert(nr_elms);
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr = array(1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
Callback Functions in JavaScript

Last accessed pages

  1. Butterfly Kyodai (17500)
  2. Remove / Get duplicate array values - Reset array keys in PHP (6584)
  3. Math Mahjong Advanced (1084)
  4. Read Excel file data in PHP - PhpExcelReader (41426)
  5. Star shapes with CSS (3431)

Popular pages this month

  1. Qwop (4726)
  2. Bubbles3 (4342)
  3. Butterfly Kyodai (3092)
  4. Zuma Deluxe (2868)
  5. Backgammon (1463)