Showing posts with label timer. Show all posts
Showing posts with label timer. Show all posts

Friday, January 16, 2009

JavaScript Timer

Well i am a novice in JavaScript, and so i started writing a simple Ad time out script. The most tricky part was to display the time along with the other text, and do transfer to the next page after time out. I learnt that we can place the html at any place

<SCRIPT type="text/javascript" LANGUAGE = "JavaScript">
<!--
var secs
var timerID = null
var timerRunning = false
var delay = 1000

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 10
    StopTheClock();
    StartTheTimer();
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false;
   
}

function StartTheTimer()
{
    if (secs < 0)
    {
        window.location = "next.html"
    }
    else
    {
        document.getElementById('timer').innerHTML=secs;
        self.status = secs
        secs = secs - 1
        timerRunning = true
        timerID = self.setTimeout("StartTheTimer()", delay)
    }
}

//-->
</SCRIPT>

Then i learned that we can use document.getElementById(<a or span or div Id) in line 32 to set the value to the current time in the html.

The way i was accessing it in the body of html is

<p class="style3">click to skip or wait for <span id="timer"></span> &nbsp;seconds&nbsp;

A Div element can be used but i get it as

click to skip or wait for
5
seconds 

So i changed it to span to get all in a single line. I read that anchor tag also works but haven’t tried it.

Another interesting thing that i learned is that we can move to the next page after time out using

window.location("next.html");

JavaScript timer code : http://www.mcfedries.com/JavaScript/timer.asp