script language="JavaScript" type="text/JavaScript"
//to store timeout ID
var tID;
function tickTimer(t)
{
//if time is in range
if(t>=0)
{
document.writeln(t);
t=t-1;
tID=setTimeout("tickTimer('"+t+"')",1000);
}
//stop the timeout event
else
{
killTimer(tID);
document.writeln("
Time Out!");
}
}
//function to stop the timeout event
function killTimer(id)
{
clearTimeout(id);
}
script
I am removing angular brackets becuase it is not accepting it please put it where needed in the javascript functions
call these function like this
body onLoad="tickTimer(10)" onUnload="killTimer(tID)"
Now let’s analyze the code:
1. We have created two functions tickTimer() and killTimer().
2. We have defined two event handlers onLoad and onUnload which’d call the respective functions at respective events.
When the code above (as a web page) is executed, it’d proceed as:
1. First the onLoad event calls tickTimer function with the initial time, the countdown timer has to be ticked down form.
2. The function displays the initial time remaining, does some calculations and calls a method setTimeout().
3. The setTimeout function now calls the function passed, every 1000 milliseconds 1 second). On setting the timeout event this method returns a unique ID which would be used to stop the timeout event when needed (onUnload or when timer has ticked down to 0).
One thing you may get confused with is how without loop or anything as such, are we able to count the timer down. Answer is, because JavaScript is an event driven language. First, we are defining a body onLoad event to make a call to some function as the web page is loaded. Second, we are defining a timeout event that would call the function itself (recursive call) every one second indefinitely until the timeout event is cleared. We are clearing the timeout either when the countdown timer reaches 0 or when the page gets unloaded (onUnload).
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment