Quantcast
Channel: CodingTalks » codingtalks
Viewing all articles
Browse latest Browse all 7

JavaScript : Countdown Timer

$
0
0

 

Well , This Post Based Upon  one of JavaScript’s powerful method getElementById(). This is documents’s method which can be used to access HTML entities within JavaScript with the help of their IDs (which is unique).

For example we can access the HTML entity and its values etc. with the ID oneas:

document.getElementById("one")

The HTML object may be defined like below:

<p id="one">some text</p>

 

Code : 

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

    &lt;html&gt;

    &lt;head&gt;

    &lt;title&gt;CodingTalks : JavaScript Countdown Timer&lt;/title&gt;

    &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt;

    &lt;script language="JavaScript" type="text/JavaScript"&gt;

    //to store timeout ID

    var tID;

    function tickTimer(t,id)

    {

    //if time is in range

    if(t&gt;=0)

    {

    document.getElementById(id).innerHTML=t;

    t=t-1;

    tID=setTimeout("tickTimer('"+t+"','"+id+"')",1000);

    }

    //stop the timeout event

    else

    {

    killTimer(tID);

    document.getElementById(id).innerHTML="Time Out!!";

    }

    }

    //function to stop the timeout event

    function killTimer(id)

    {

    clearTimeout(id);

    }

    &lt;/script&gt;

    &lt;!--style the ID --&gt;

    &lt;style&gt;

    #timer

    {

    background: #000;

    color: #fff;

    font-size: 20px;

    }

    &lt;/style&gt;

    &lt;/head&gt;

    &lt;!--pass the id to timer has to attached to --&gt;

    &lt;body onLoad="tickTimer(59,'timer')" onUnload="killTimer(tID)"&gt;

    &lt;p&gt;Timer: &lt;span id="timer"&gt;&lt;/span&gt;&lt;/p&gt;

    &lt;/body&gt;

    &lt;/html&gt;

 

 

Tutorial By : Manoj Kataria

Java Developer

 

The post JavaScript : Countdown Timer appeared first on CodingTalks.


Viewing all articles
Browse latest Browse all 7

Trending Articles