JavaScript

JavaScript Count Up Timer

Timers play a great role in organizing our lifestyle to a great extent. For instance, measuring time intervals, keeping a track of the elapsed time, and remaining time in case of a race, competition, etc. In such cases, implementing a count up timer proves to be an effective tool for handling such types of scenarios for appropriate time management.

How to Implement a Count Up Timer in JavaScript?

The following approaches can be utilized to implement a count up timer in JavaScript:

In the section below, the mentioned approaches will be illustrated one by one!

Approach 1: Implement a Count Up Timer in JavaScript Using the setInterval() and Math.floor() Methods

The “setInterval()” method is applied to set a specific time interval upon a specific function to execute and the “Math.floor()” method returns the nearest down integer value. These methods can be implemented to apply a time interval to a particular function and perform precise calculations for the proper execution of the timer.

Syntax

setInterval(function, milliseconds)

In the above syntax:

  • function” refers to the function on which the time interval will be applied and “milliseconds” points to the set time interval.

The “Math.floor()” method takes the “value” to be formatted as its parameter.

Example

Go through the following code snippet for understanding the stated concept:

<center><body>

<h3 id= "countup">00:00:00</h3>

<button id="stoptimer" onclick="clearInterval(timer)">Stop Timer</button>

</body></center>

In the above demonstration,

  • Specify the heading containing the format of the count-up timer.
  • After that, create a button with an attached “onclick” event redirecting to the function “clearInterval()” method having the variable “timer” passed as its parameter which contains the “setInterval()” method. This will result in clearing the set time interval upon the button click.

Now, go through the following JavaScript code snippet:

var seconds = 0

var timer = setInterval(upTimer, 1000);

function upTimer() {

++seconds;

var hour = Math.floor(seconds / 3600);

var minute = Math.floor((seconds - hour * 3600) / 60);

var updSecond = seconds - (hour * 3600 + minute * 60);

document.getElementById("countup").innerHTML = hour + ":" + minute + ":" + updSecond;

}

In the above code:

  • Initialize the seconds with “0”. Also, apply the setInterval() method on the function upTimer() with a time interval of “1000” milliseconds.
  • After that, define a function named “upTimer()”. In its definition, compute the “hour” by dividing it by the number of seconds in an hour and return the nearest down integer value using the “Math.floor()” method.
  • Similarly, compute the minutes by dividing the subtraction of both (the passed seconds in the timer and the number of seconds in an hour) by the total minutes in an hour.
  • The calculation for incrementing the seconds in the timer will be calculated in the last step.
  • All the above-discussed approaches can be evident as follows:

Working of Timer:

Approach 2: Implement a Count Up Timer in JavaScript Using the setInterval() and parseInt() Methods

The “setInterval()” method is similarly applied to set a specific time interval upon a particular function to execute and the “parseInt()” method parses a value as a string and returns the first integer. These methods can be implemented such that the function executes at a particular interval and displays the timer count by parsing the digits properly in it.

Syntax

setInterval(function, milliseconds)

In the above syntax:

  • function” refers to the function on which the time interval will be applied and “milliseconds” points to the set time interval.
parseInt(string, radix)

In the given syntax:

  • string” refers to the string to be parsed.
  • radix” value is “10” by default

Example

The below-given demonstration explains the stated concept:

<center><h3>Count Up Timer For One Hour</h3>

<div>

<h3 id = "countup"></h3>

<span id="minutes">Minutes</span>:<span id="seconds">Seconds</span>

</div></center>

In the above HTML code:

  • Within the “<center>” tag, specify the heading.
  • After that, include the “<span>” tag to accumulate the count up timer here with respect to the specified formatting for “minutes” and “seconds”.

Now, go through the following js code snippet:

var second = 0;

function upTimer ( count ) { return count > 9 ? count : "0" + count; }

setInterval( function(){

document.getElementById("seconds").innerHTML= upTimer(++second % 60);

document.getElementById("minutes").innerHTML= upTimer(parseInt(second / 60, 10));

}, 1000);

In this part of the code:

  • Initialize the “seconds” with 0.
  • After that, define the function named “upTimer()”.
  • This function adds a leading zero and applies a check if the value passed to it is a single digit i.e (<9). In such a case, it adds a leading zero.
  • The “setInterval()” method with a set interval of “1000” ms will be applied to the further code. Here, the specified “span” element for the seconds and the minutes will be accessed respectively.
  • For “seconds”, the initialized seconds are incremented and the 60 points to the end limit for seconds. After that, they are passed as a parameter to the function upTimer() and displayed in the DOM as a span time discussed before.
  • Similarly, in the case of “minutes”, compute the minutes. Also, apply the “parseInt()” method to parse the minutes. The first parameter in the method indicates the transition of the minute at the second i.e 60. The second parameter as described in the syntax is by default set to 10

Executing the above code will produce the following results on the browser:

It can be observed from the output that the count up timer is working perfectly.

Approach 3: Implement a Count Up Timer in JavaScript Using the jQuery Approach

In this approach, jQuery can be applied using its methods to perform the given requirement.

Syntax

$(selector).html()

In the given syntax:

  • selector” refers to the “id” against the html element.

Example

The following lines of code explain the stated concept.

<script src= "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<center><h3>Count Up Timer For 30 Minutes</h3>

<div id = "countup">

<span id= "minutes">Minutes</span>:<span id= "seconds">Seconds</span>

</div></center>

In the above-given example,

  • First, include the “jQuery” library.
  • Now, similarly, repeat the above-discussed approach for specifying the “minutes” and “seconds” in the “<span>” tag.
var second = 0;

function upTimer (count) { return count > 9 ? count : "0" + count; }

setInterval( function(){

$("#seconds").html(upTimer(++second % 60));

$("#minutes").html(upTimer(parseInt(second / 30, 10)));

}, 1000);

In the above js code:

  • Similarly, initialize the seconds with “0”.
  • Now, declare a function named “upTimer()”.
  • In its definition, revive the steps for applying a check on the number of digits.
  • Likewise, apply the “setInterval()” method with a “1000” milliseconds time interval on the specified function.
  • Here, apply the jQuery “html()” method to return the content (innerHTML) of the elements by referring to them as “seconds”, and “minutes” respectively.

Output

In this write-up, all the approaches to create a count-up timer are illustrated.

Conclusion

The combination of “setInterval()” and “Math.floor()” methods, the “setInterval()” and “parseInt()” methods or the “jQuery” approach can be utilized to implement a count up timer using JavaScript. The setInterval() and the Math.floor() methods can be implemented to apply a specific time interval to a particular function and perform accurate calculations for the proper execution of the timer. The setInterval() and the parseInt() methods can be used to execute a function at specific intervals repeatedly and display the timer count properly. The jQuery approach can be applied to integrate the HTML element and perform the required functionality. This article demonstrated to implementation of a count up timer in JavaScript.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.