This time , let’s start off with the code first:
Now let’s analyze the code:
1. We have created two functions
2. We have defined two event handlers
onUnload which’d call the respective functions at respective
When the code above (as a web page) is executed, it’d proceed as:
1. First the
onLoad event calls
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 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,
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
But as it is, can we embed or place the above timer in a web page the way we want, styled and perfectly aligned. Or how about a single number getting counted down rather than showing all the numbers as the countdown proceeds. We’ll see that in the next post!