Table of Contents
JavaScript makes it very simple to create complex features in your web applications.
One of the most common features is a timer that counts how much time has elapsed.
In this post, we'll learn how to create a timer in JavaScript like the one below:
How to Create a Timer in JavaScript
To create a timer, let's first start of with the HTML markup:
HTML<div class="timer">
<div class="time">00:00</div>
<button class="trigger" onClick="toggleTimer()">Start</button>
</div>
In our HTML, we have the overall timer container, a div that will display the time, and a button that will start and stop the timer.
Let's add some styles to this:
CSS.timer {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin: auto;
width: 16rem;
height: 16rem;
border: 1px solid #ccc;
border-radius: 50%;
background: white;
font-family: sans-serif;
}
.time {
font-size: 2rem;
font-weight: bold;
}
.trigger {
margin-top: 1rem;
padding: 0.5rem 1rem;
border: 1px solid lightgray;
border-radius: 4px;
background: white;
cursor: pointer;
}
Here's how this looks so far:
Now it's time (get it?) for the JavaScript.
Let's start by querying for the elements we need:
JAVASCRIPTconst time = document.querySelector(".time");
const trigger = document.querySelector(".trigger");
Add an event listener to the trigger button:
JAVASCRIPTconst toggleTimer = () => {};
trigger.addEventListener("click", toggleTimer);
We need to keep track of the time, so let's create a variable to store the time:
JAVASCRIPTlet timeElapsed = 0;
Now, to actually keep track of time, we'll need to use the setInterval function.
This function takes two arguments: a callback function and a time interval.
Inside the callback function, we'll increment the time by 1 second:
JAVASCRIPTconst toggleTimer = () => {
setInterval(() => {
timeElapsed += 1;
}, 1000);
};
So far we have this:
JAVASCRIPTconst time = document.querySelector(".time");
const trigger = document.querySelector(".trigger");
let timerInterval;
let timeElapsed = 0;
const toggleTimer = () => {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
} else {
timerInterval = setInterval(() => {
timeElapsed += 1;
}, 1000);
}
};
trigger.addEventListener("click", toggleTimer);
Now all we need to do is update the time on the page and the text on the trigger button:
JAVASCRIPTconst formatTime(seconds) => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
const formattedSeconds = remainingSeconds < 10 ? "0" + remainingSeconds : remainingSeconds;
const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;
return formattedMinutes + ":" + formattedSeconds;
};
const toggleTimer = () => {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
trigger.innerText = "Start";
} else {
timerInterval = setInterval(() => {
timeElapsed += 1;
time.innerText = formatTime(timeElapsed);
}, 1000);
trigger.innerText = "Stop";
}
};
Here's the full code:
JAVASCRIPTconst time = document.querySelector(".time");
const trigger = document.querySelector(".trigger");
let timerInterval;
let timeElapsed = 0;
const formatTime = (seconds) => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
const formattedSeconds = remainingSeconds < 10 ? "0" + remainingSeconds : remainingSeconds;
const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;
return formattedMinutes + ":" + formattedSeconds;
};
const toggleTimer = () => {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
trigger.innerText = "Start";
} else {
timerInterval = setInterval(() => {
timeElapsed += 1;
time.innerText = formatTime(timeElapsed);
}, 1000);
trigger.innerText = "Stop";
}
};
trigger.addEventListener("click", toggleTimer);
Here is the final result in the demo below:
Conclusion
In this post, we learned how to create a simple timer using JavaScript.
We used the setInterval function to keep track of time and the clearInterval function to stop the timer to let the user control the timer.
Thanks for reading!
Managing PHP Dependencies with Composer
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
Getting Started with Deno
How to deploy a MySQL Server using Docker
Getting Started with Sass
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up a Local Web Server using Node.js
