Tuesday, December 28, 2010

Callback Functions

A function can be sent as a parameter to another function. The function that is being sent as a parameter to be executed in later stage is called callback functions. The main function that is being executed will call this callback function as needed.In Javascript whenever you call a function, that function get executed in scope of calling function. To execute a function under given scope:

functionName.call(scopeReference, params);

in above example function "functionName" is being executed in scope of "scopeReference".
These kind of callback functions is the heart of EventListening in Javascript. While adding EventListeners it accepts another function as a parameter, that is a callback function that needs to be called while particular event occurs. for example:
document.addEventListener("click", console.log, false);
Here console.log is a callback function, which supposed to be called whenever user click on document (browser window).

Another example of using callback functions are setTimeOut() and setInterval() calls. One thing that needs to be observed here is whenever a function is passed as an argument, function name without parenthesis is passed. because adding parenthesis will execute the function immediately and pass returned object. By removing parenthesis, calling function will get just reference to the callback function.

No comments:

Post a Comment