Home >>Javascript Tutorial >How to create a countdown timer in jquery

How to create a countdown timer in jquery

Create a countdown timer in jQuery

First we need to include the jQuery library file to the HTML page to perform this task.

To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery.

We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy.

As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag.

Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;”.

Now we need to put the condition if timer got finished (if (time ==0)) then redirect to the page we want.

Jquery Script

<script type="text/javascript" src="jquery-1.6.2.min.js"></script>

<h1 align="center" style="color:green">A countdown timer in jquery</h1>

<h3 style="color:#FF0000" align="center">
 You will be logged out in : <span id='timer'></span>
 </h3>

<script>
	//define your time in second
		var c=60;
        var t;
        timedCount();

        function timedCount()
		{

        	var hours = parseInt( c / 3600 ) % 24;
        	var minutes = parseInt( c / 60 ) % 60;
        	var seconds = c % 60;

        	var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);

            
        	$('#timer').html(result);
            if(c == 0 )
			{
            	//setConfirmUnload(false);
                //$("#quiz_form").submit();
				window.location="logout.html";
			}
            c = c - 1;
            t = setTimeout(function()
			{
			 timedCount()
			},
			1000);
        }
	</script>

Logout.html

<h1 style="color:Red">Your session time expired</h1>

No Sidebar ads