Sunday, January 16, 2011

Countdown javascript timer

After being desperate from finding any piece of javascript code to implement a countdown timer online, I tried to inhance an ordinary counter to fullfill my specific need.

I needed a countdown timer, to appear to students in an online exam, the exam will be automatically closed when the time runs out.

Although I could have used the same javascript timer to end the exam, I prefered to use a server-side ajax timer to check if the time of the exam had expired and finish it, the reason behind using the server-side is to prevent the manipulation of the exam time since the javascrip code depends on the local clock of the client, if they changed the time; the period will be expanded :D.

function sivamtime() {

' 1. retrieve and keep the current time from the client side clock.
now=new Date();

hour=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();

' Retrieve exam period and exam starting time from a field on the web page. (Save and calculate the values on the page load; the values must be the total seconds on the time span for example if the start time is 09:27:05 the value will be [09*60*60 + 27*60 + 05 = 293225])
var examTime=document.getElementById('txtExamTime').value;
var startexamTime=document.getElementById('txtStartTime').value;

'Calculate how many seconds has passed from the beginning of the exam; and which equals [current time in seconds] - [start time of the exam in seconds] and substract the result from the [exam total duration in seconds].
var currentTime;
var SecondsFromStart;
var timeLeft;
var hours=0;
var minuts=0;
var seconds=0;
var h=0;
var m=0;
var s=0;
var time;
currentTime=0;
currentTime=hour*60*60;
currentTime=currentTime+(min*60);
currentTime=currentTime+sec;
SecondsFromStart=currentTime-startexamTime;
timeLeft=examTime-SecondsFromStart;

' check if the exam has finished.
if (SecondsFromStart > examTime)
{
document.getElementById('txtTime').value="00:00:00";
}
else
'otherwise calculate and show the remaining time.
{
hours=Math.floor(timeLeft/3600);
m=(timeLeft/3600)-hours;
minuts=Math.floor(m*60);
s=((m*60)-minuts);
seconds=Math.floor(s*60);

if (hours<=9) { hours = "0" + hours; } if (minuts<=9) { minuts = "0" + minuts; } if (seconds<=9) { seconds = "0" + seconds; } time = hours + ":" + minuts + ":" + seconds; document.getElementById('txtTime').value=time; ' recall this function every 500 millisecond
setTimeout("sivamtime()", 500);
}
}

' The following function will be called onload to save the start time.
function SetDateTime()
{
now=new Date();
hour=now.getHours();
min=now.getMinutes();
sec=now.getSeconds();
currentTime=0;
currentTime=hour*3600;
currentTime=currentTime+(min*60);
currentTime=currentTime+sec;
document.getElementById('txtStartTime').value=currentTime;
sivamtime();
}

One last thing, do not forget to end the exam, from the code behind ajax timer at the end of the time.

happy coding!

No comments: