How to make a countdown timer using JavaScript

Web programming topics
Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to make a countdown timer using JavaScript

Post by Saman » Thu Jun 16, 2011 1:15 am

Here is a quick code that I worked out. You need to change var targetDate = "12 December, 2012 12:00:00"; for the desired date/time.

Code: Select all

<html>
<!--
Created by ROBOT.LK - https://robot.lk
-->
<head>
<title>JavaScript Countdown Timer - ROBOT.LK</title>

<script language="javascript" type="text/javascript">
var Timer;
var TotalSeconds;
var targetDate = "12 December, 2012 12:00:00";

function CreateTimer(TimerID) {
    Timer = document.getElementById(TimerID);
    
    today  = new Date();
    todayEpoch  = today.getTime();

    target = new Date(targetDate); 
    targetEpoch = target.getTime();
    
    TotalSeconds = (targetEpoch - todayEpoch)/1000; // get difference and convert to seconds
    
    
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function Tick() {
    TotalSeconds -= 1;
    UpdateTimer();
    
    if (Math.floor(TotalSeconds) <= 0){
        Timer.innerHTML = "We Have Reached The Target";
    }
    else{
        window.setTimeout("Tick()", 1000);
    }
}


function LeadingZero(Time) {
    return (Time < 10) ? "0" + Time : Time;
}

function UpdateTimer() {
    var Seconds = TotalSeconds;
    
    var Days = Math.floor(Seconds / 86400);
    Seconds -= Days * 86400;

    var Hours = Math.floor(Seconds / 3600);
    Seconds -= Hours * (3600);

    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);
    
    Seconds = Math.floor(Seconds);

    var TimeStr = ((Days > 0) ? Days + " Days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)

    Timer.innerHTML = TimeStr + " More Remaining Till " + targetDate + "... Are You Ready?";
}
</script>

<!-- Created by ROBOT.LK - https://robot.lk -->

</head>

<body>

<!-- Place where you need to print the countdown timer message -->
<h1><div id='timer'></div></h1>

<script type="text/javascript">window.onload = CreateTimer("timer");</script> 

</body>
</html>
Enjoy!
Post Reply

Return to “Web programming”