03 July 2011

How to add a timer using Javascript in a webpage?

Have your ever taken an online exam , you might have seen a timer where after appropriate time it automatically submits the form and redirects you to next page, today through this post , I will explain you this whole functionality in detail

Here we need 2 things

1: Simple HTML form :- 
We will create a simple html form with one question , 2 radio buttons and a submit button, it will look like this

<form name = “question” action = “next.php” method = “post”>
1:- What is Chemical name of hydrogen?
<input type = “radio” name = “ans” value = “Hydrogen” >Hydrogen
<input type = “radio” name = “ans” value = “Helium” >Helium
<input type = “hidden” value =”1600” id  =”hdnTimer”>
<input type = “submit”>
</form>

2:- Next comes script part , so here is your script

<script type = 'text/javascript'>
function MyTimer() {
var valueTimer = $('#hdnTimer').val();
if(valueTimer > 0){
       valueTimer = valueTimer - 1; 
       secs  = ((valueTimer % 3600) % 60).toString();
       if(secs.length  == 1) secs  = '0' + secs;
      $('#idTimerLCD').text('Time Left :' + secs + ' sec' ); 
       $('#hdnTimer').val( valueTimer ); 
 }  else {
       $('#Question').submit(); // Submit form as soon as timer complete
}
}

// This is used to call MyTimer() as soon as body loads and after every 1 sec
$("body") . ready(function(){
setInterval( "MyTimer()" , 1000);
});
</script>


Note here i have used jquery , so you need to download it from their official site and add it to your page

So this is what you all need to add a timer in your application , now enjoy , if still have some query , then feel free to ask :)