How to use a timer in JavaScript

Problem

You are designing a web page and wish to add interactivity that will be occurring periodically. For example, it will be sending a request to an API every 10 seconds to retrieve information. For this post, we will use an example of updating a number incrementally every second.

Solution

When you write Javascript in a web browser, the web browser offers some built-in functions to help you accommodate your needs. One of these functions is setInterval and is used for setting up a timer running in the background. The timer simply accepts 2 arguments:

  1. The action to execute (a javascript function)
  2. The interval/ period that the timer will use for ticking (in milliseconds, 1 second = 1000ms)

In our example we will need a function that will simply update a number and the interval of 1 second that is 1000ms.

But first, let’s create a simple HTML page that will have a text input element with initially having a the 0. That number will then get updated on every second. The timer will start by clicking a button.

HTML
<html !DOCTYPE>
	
	<head>

	</head>

	<body>
		<h3>Timer example</h3>
		<hr/>

		<input type="text" id="txtNumber" value="0"/>
		<input type="button" value="start timer"/>

	</body>

</html>

Now, let’s add the onclick event on the button. When the user clicks on the button, a JavaScript function will set up and start the timer.

<input type="button" value="start timer" onclick="startTimer()" />

We use a function called startTimer() and is defined as follows:

function startTimer(){
    let timer = setInterval(incrementNumber, 1000);
}

The incrementNumber() is another one function responsible for updating the number in the text field by one. It is defined as follows:

function incrementNumber() {
    let currentNumber = document.getElementById("txtNumber").value;
    let nextNumber = parseInt(currentNumber) + 1;
    document.getElementById("txtNumber").value = nextNumber;
}

Putting both functions under a script tag.

<script>
	function incrementNumber() {
		let currentNumber = document.getElementById("txtNumber").value;
		let nextNumber = parseInt(currentNumber) + 1;
		document.getElementById("txtNumber").value = nextNumber;
	}
	function startTimer(){
		let timer = setInterval(incrementNumber, 1000);
	}
</script>

The complete code is as follows:

<html !DOCTYPE>
	
<head>

</head>

<body>
	<h3>Timer example</h3>
	<hr/>

	<input type="text" id="txtNumber" value="0"/>
	<input type="button" value="start timer" onclick="startTimer()" />

</body>

<script>
	function incrementNumber() {
		let currentNumber = document.getElementById("txtNumber").value;
		let nextNumber = parseInt(currentNumber) + 1;
		document.getElementById("txtNumber").value = nextNumber;
	}
	function startTimer(){
		let timer = setInterval(incrementNumber, 1000);
	}
</script>

</html>

Output

And when clicking the button, the 0 gets updated by 1 every second.

It works!

Conclusion

In this post, we quickly saw how to use the setInterval function in JS and increment a number in a text field by 1 every second. You can download the code below.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.