Categories
JavaScript Answers

How to create a plain count up timer in JavaScript?

Spread the love

Sometimes, we want to create a plain count up timer in JavaScript.

In this article, we’ll look at how to create a plain count up timer in JavaScript.

How to create a plain count up timer in JavaScript?

To create a plain count up timer in JavaScript, we use the setInterval function.

For instance, we write

<label id="minutes">00</label>:<label id="seconds">00</label>

to add the label elements for the minutes and seconds displays.

Then we write

const minutesLabel = document.getElementById("minutes");
const secondsLabel = document.getElementById("seconds");
let totalSeconds = 0;

const setTime = () => {
  ++totalSeconds;
  secondsLabel.innerHTML = (totalSeconds % 60).toString().padStart(2, "0");
  minutesLabel.innerHTML = parseInt(totalSeconds / 60)
    .toString()
    .padStart(2, "0");
};

setInterval(setTime, 1000);

to select the elements with getElementById.

Then we define the setTime function that updates the elements by getting the seconds with totalSeconds % 60.

We prepend a 0 before it when its length is less than 2.

Likewise, we get the minutes with totalSeconds / 60 and call padStart to prepend a 0 before it when its length is less than 2.

We set innerHTML of the elements to display the numbers.

Conclusion

To create a plain count up timer in JavaScript, we use the setInterval function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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