How to Create an Animated Counter Number Using setTimeout() in JavaScript

An animated counter number is a great way to display numerical data in a visually engaging way. By using JavaScript, we can create a smooth and dynamic animation that increases the displayed number gradually from zero to a specified target value.


In this tutorial, we'll walk you through the steps of creating an animated counter number using setTimeout() in JavaScript. We'll start by creating the HTML and CSS needed to display the counter number on your website. Then, we'll use JavaScript to animate the counter number to gradually increase from zero to the desired value.


Setting Up the HTML and CSS

Let's start by creating the HTML and CSS needed to display the counter number on your website. We'll create a simple HTML structure consisting of a container element and a span element to display the number. We'll also add some basic CSS to style the counter number:


Here, we've set the container element to fill the entire viewport and center the child element vertically and horizontally. We've also styled the counter number to have a large font size, bold text, and a neutral color.


Animating the Counter Number

Now that we have the HTML and CSS set up, let's use JavaScript to animate the counter number. We'll start by selecting all elements with the class "count" and looping through them using forEach()


Inside the loop, we'll create variables to store the target count value, the initial count value (which is zero), and the increment value for each animation step.


Here, we're using the dataset property to retrieve the target count value from the "data-count" attribute of the span element. We're also using the + operator to convert the inner text of the span element to a number.


Next, we'll define a function called updateNumber() that will be called repeatedly using setTimeout() to animate the counter number.


Inside the updateNumber() function, we'll increment the initial count value by the increment value and update the inner text of the span element to reflect the new value.


Subscribe - Thapa Technical