You have already been exposed to and used Higher-order Functions sometimes also known as Callback Functions.
For our purposes, we will currently define a Callback Function as being a function you pass to another function, with the goal that the other function will eventually call it.
// passed in as a function declaration
otherFunc1("some value", function(){alert("haha")} );
// passed in as a function reference
otherFunc2("some value" callBackFunction );
One common use of callback functions in web-based javascript is in timers.
A timer is a function that waits some specified amount of time then does something.
Timers may be used to refresh elements of a page at set intervals, change the picture in a gallery, add a “pop-up”, etc.
One built in timer function setTimeout()
, which takes as a minimum two input parameters;
setTimeout( functionToCall, timeToWait );
In the following example of the setTimeout()
function, it is used to call another function after 3 seconds, which changes the background color of the example page and creates a popup alert.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
Like setTimeout()
the setInterval()
function can be used to execute a supplied callback function after a specified amount of time. The major difference is that setInterval()
creates a reoccurring callback that is executed constantly, at the interval specified.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
You can cancel a timer function, by passing a reference to the timer function to the appropriate clear function (i.e. clearTimeout()
and clearInterval()
).
To pass a a reference to a timer function, simply create a binding that references the function and pass that to the appropriate clearing function. In the following example, a single timer (i.e. setTimeout()
) is used to stop the reoccurring, setInterval()
timer after 5 seconds.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
Please read the following from w3schools;
Again, a callback is just a function that is passed to another function, so that it can later be called back and executed. As we move forward this week, you will be working a lot with callback functions.