A countdown timer using javascript

Here is my version of a countdown timer using a few lines of Vanilla Javascript.

Steps to create a countdown time using Javascript
  • Create an input button with a value “Start Timer”.
  • Create an input text field where the user can input the time to do the countdown.
  • Add a function on the click event of the button.
  • Get the value the user input in the text field.
  • Using the isNaN function, check if the value is a number of not.
  • Use setInterval function to call a custom function to generate the time.
  • Using simple logic and the Math object, the time is converted into minutes:seconds format.
  • Input the time into the HTML element below the text field and button, created for displaying time.
  • Check to find out if the time is done and alert the user, else continue to reduce the time and display.

A sampling of the code.

function tick(){
var timeDisplay=document.getElementById("time");
var min=Math.floor(mySeconds/60);
var sec=mySeconds-(min*60);
if (sec < 10) {
sec="0"+sec;
}
var message=min.toString()+":"+sec;
timeDisplay.innerHTML=message;
if(mySeconds===0){
alert("Done");
clearInterval(intervalHandle);
resetPage();
}
mySeconds--;
}

I hope you found this article interesting.

Let me know if you have any questions or comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Endorsed by these folks ...

Femy’s a great front-end developer with excellent capabilities in XHTML/CSS/Javascript. She’s especially skilled with skinning ASP.Net websites–working in Visual Studio with .Net’s built-in controls and Telerik’s Rad Control package.

Arthur Wait VP, Engineering, Solutionset