blog-a-countdown-timer-using-javascript

A countdown timer using javascript

Posted on:

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 of 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 the 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.