![]() |
JavaScript - Delayed Actions
|
|
|
Occasionally on a web page you need to be able to fire an action after a given period of time, or at repeating intervals. Try clicking on this link and see what happens. So, how is this done ? The <a> link above has an effectively null destination and just uses the onclick event handler attribute to call a function, as shown in the HTML below.
<a href="#" onclick="return setTimer()">this link</a> The return in the event handler code is important, why is explained later. In the function called by the link, setTimer, you create the timer, which is set to go off after a number of milliseconds (you decide how many), 1000 (1 second) in this case.
<script language="javascript">
function setTimer() {
window.setTimeout("showAlert('This was delayed by 1 second')",1000);
return false;
}
</script>
The setTimeout call creates the timer, initialized with the given arguments, and returns an identifier for it, which in this example is ignored. The first argument is the code snippet that will be executed when the timer fires, the second argument is the delay in milliseconds before the code is executed. Note the use of a return false; statement in the setTimer function. The returned value is used by the onclick event handler in the link as shown earlier. As the value is false the navigation actions normally carried out by the browser when a link is clicked are suppressed, thus leaving the page location unchanged. The returned identifier from setTimeout can be saved to a variable so that the timer can be cancelled before it has fired, should this be necessary. This is illustrated in the example using the aTimer variable and by the parameter supplied to the cancelTimer function, which would be supplied as aTimer.
<script language="javascript">
var aTimer;
function setTimer() {
aTimer = window.setTimeout("showAlert('This was delayed by 1 second')",1000);
return false;
}
...
function cancelTimer(t){
window.clearTimeout(t);
}
</script>
Repeating ActionsUsing setTimeout is easy for one off action delays, but what happens if the action needs to be performed repeatedly. One answer would be to reset the timer via another call to setTimeout, which is a perfectly acceptible thing to do. However, there is another timer function available, namely setInterval. This function, which takes the same arguments as setTimeout does, executes the given code snippet repeatedly until cleared using clearInterval.
<script language="javascript">
var aTimer;
function setRepeater() {
aTimer = window.setInterval("showAlert('This was delayed by 1 second')",1000);
return false;
}
...
function cancelRepeater(t){
window.clearInterval(t);
return false;
}
</script>
Using this link you can see the result of creating a repeating timer. It will repeatedly show an alert box until this link is clicked to clear the timer. |
|
Content of this page Copyright © Robert Quince 1996 - 2005. |