JavaScript Countdown Timer Code

JavaScript Countdown Timer Code
Project: Simple Pure JS Countdown Timer
Author: jmikey
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create a countdown timer. The timer displays the time remaining in minutes and seconds, updating every second using the “tick” function. When the timer reaches zero, an alert message pops up and the page is reset using the “resetPage” function. The input form for setting the timer is initially displayed, and when the countdown starts, it is hidden. The code uses setInterval and clearInterval methods to manage the countdown timer.

How to Create JavaScript Countdown Timer

First of all, create two divs elements with the id attribute of “inputArea” and “time” respectively. Wrap both div into a container as follows:

<div id="container">
	<div id="inputArea"></div>
	<div id="time">0:00</div>
</div>

After that, style the timer according to your needs.

body { font-family: sans-serif;color:#333;}
#container { width:400px;margin:auto;}
h1 { font-size:5em;}

Finally, add the following JavaScript timer function to your project.

var secondsRemaining;
var intervalHandle;

function resetPage(){

	document.getElementById("inputArea").style.display = "block";

}

function tick(){
	// grab the h1
	var timeDisplay = document.getElementById("time");

	// turn the seconds into mm:ss
	var min = Math.floor(secondsRemaining / 60);
	var sec = secondsRemaining - (min * 60);

	//add a leading zero (as a string value) if seconds less than 10
	if (sec < 10) {
		sec = "0" + sec;
	}

	// concatenate with colon
	var message = min.toString() + ":" + sec;

	// now change the display
	timeDisplay.innerHTML = message;

	// stop is down to zero
	if (secondsRemaining === 0){
		alert("Done!");
		clearInterval(intervalHandle);
		resetPage();
	}

	//subtract from seconds remaining
	secondsRemaining--;

}

function startCountdown(){

	function resetPage(){
		document.getElementById("inputArea").style.display = "block";
	}

	// get countents of the "minutes" text box
	var minutes = document.getElementById("minutes").value;
	
	// check if not a number
	if (isNaN(minutes)){
		alert("Please enter a number");
		return; // stops function if true
	}

	// how many seconds
	secondsRemaining = minutes * 60;
	
	//every second, call the "tick" function
	// have to make it into a variable so that you can stop the interval later!!!
	intervalHandle = setInterval(tick, 1000);

	// hide the form
	document.getElementById("inputArea").style.display = "none";


}

window.onload = function(){

	// create input text box and give it an id of "min"
	var inputMinutes = document.createElement("input");
	inputMinutes.setAttribute("id", "minutes");
	inputMinutes.setAttribute("type", "text");
	
	//create a button
	var startButton = document.createElement("input");
	startButton.setAttribute("type","button");
	startButton.setAttribute("value","Start Countdown");
	startButton.onclick = function(){
		startCountdown();
	};

	//add to the DOM, to the div called "inputArea"
	document.getElementById("inputArea").appendChild(inputMinutes);
	document.getElementById("inputArea").appendChild(startButton)		

}

Code Explanation

The code for the timer function consists of four functions: resetPage, tick, startCountdown, and an anonymous function attached to the window.onload event. Here’s a breakdown of what each function does:

  1. resetPage: This function is responsible for resetting the page by making the “inputArea” div visible when the timer is finished. It achieves this by setting the CSS display property of the “inputArea” div to “block”.
  2. tick: This function updates the display of the timer every second. It first retrieves the “time” div element from the HTML document, and then calculates the minutes and seconds remaining in the countdown timer using the Math.floor function. It then concatenates these values into a string and sets the text content of the “time” div to this string. If the timer has reached zero, the function stops the interval and calls the resetPage function.
  3. startCountdown: This function is called when the user clicks the “Start Countdown” button. It retrieves the value of the “minutes” text input field, and if it is not a number, it displays an error message using the alert function and returns. Otherwise, it calculates the number of seconds remaining and starts the countdown by calling the setInterval function and passing it the tick function as the callback. It also hides the “inputArea” div by setting its CSS display property to “none”.
  4. window.onload: This function runs when the window loads and sets up the initial state of the page. It creates an “input” element for the minutes field, a “Start Countdown” button, and attaches a click event listener to the button that calls the startCountdown function. It then appends these elements to the “inputArea” div.

That’s all! hopefully, you have successfully created a countdown timer using this JavaScript code snippet. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply