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

2 comments:

Sajjan Sarkar said...

Here's another way to do this without javascript (for those who have turned off javascript )

include this in ur HTML HEAD section
meta HTTP-EQUIV="REFRESH" content="5; url=http://www.yourdomain.com/index.html"

the content attribute specifies how many seconds you want the current page to wait before the redirect.

Good Stuff Mr.Kolli! It IS gonna be pretty!

kolli said...

Well thats awesome.Thanks man..
I am pretty dumb in javascript back then (even now though..). Hope you can go through my other posts and comment on them too..