How to animate number increase in JavaScript?

Wondering how to animate number increase in JavaScript? This article is indeed for you!

In this article, we will explore different techniques and approaches to animating number increases or animating number counters in JavaScript.

We will provide you with the knowledge and tools to bring your web projects to life.

Different ways to animate number increase or animating number counters in JavaScript

To make a number increase animation in JavaScript, you need to change the value of a variable and keep updating it over time.

This creates a smooth animation effect. There are different ways to do this, each with its own advantages and uses.

Let’s look at some popular techniques.

1. Use setInterval function

To animate number increase or animating number counters in JavaScript, you can use the setInterval() function. It lets you repeatedly run a function or execute a code at regular intervals.

Here’s a simple guide to animate a number increase using setInterval():

var interval = setInterval(function() {
    $('#number').text(number);
    if (number >= target) clearInterval(interval);
    number++;
}, 30);

Here’s the complete example code:

<!DOCTYPE html>
<html>
<head>
    <title>Animate Number Increase</title>
    <style type="text/css">
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        #number {
            font-size: 72px;
            font-weight: bold;
            text-align: center;
            border: 1px solid black;
            padding: 20px;
        }
        #start {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div id="number">0</div>
    <button id="start">Start</button>

    <script type="text/javascript">
        var target = 50;
        var number = 0;
        var interval;

        document.getElementById('start').addEventListener('click', function() {
            clearInterval(interval);
            number = 0;
            interval = setInterval(function() {
                document.getElementById('number').textContent = number;
                if (number >= target) clearInterval(interval);
                number++;
            }, 30);
        });
    </script>
</body>
</html>

In the provided JavaScript code, the setInterval function is utilized to increase the value of the number variable by 1 every 30 milliseconds until it reaches the desired target value of 50.

Once the page loads, the animation begins automatically and showcases each number increment. The setInterval function returns an interval ID, which can be used with the clearInterval function to halt the interval and stop the animation.

Here’s the output:

2.Use the requestAnimationFrame()

The requestAnimationFrame() is an alternative method to animate number increases in JavaScript.

Unlike setInterval(), requestAnimationFrame() aligns with the browser’s refresh rate, leading to smoother animations.

Here’s an example of how you can utilize requestAnimationFrame():

<!DOCTYPE html>
<html>
<head>
    <title>Animate Number Increase</title>
    <style type="text/css">
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        #number {
            font-size: 72px;
            font-weight: bold;
            text-align: center;
            border: 1px solid black;
            padding: 20px;
        }
        #start {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div id="number">0</div>
    <button id="start">Start</button>

    <script type="text/javascript">
        let number = 0;
        let target = 80;

        function animateNumberIncrease() {
            if (number >= target) return;
            number += 1;
            document.getElementById("number").textContent = number;
            requestAnimationFrame(animateNumberIncrease);
        }

        document.getElementById('start').addEventListener('click', function() {
            number = 0;
            animateNumberIncrease();
        });
    </script>
</body>
</html>

In the JavaScript code given, whenever the button is clicked, the number variable is incremented by 1 using the requestAnimationFrame function. This continues until the value reaches 80.

If the button is clicked again, the number variable is reset to 0, and the animation begins anew.

Here’s the output:

3. Use a JavaScript animation library

If you’re looking for a more advanced and comprehensive solution, you have the option to use a JavaScript animation library such as GSAP (GreenSock Animation Platform) or Anime.js.

These libraries offer a plethora of animation features, including the ability to animate number increases.

Here’s an example of how you can achieve this using GSAP:

<!DOCTYPE html>
<html>
<head>
    <title>Animate Number Increase with GSAP</title>
    <style type="text/css">
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        #number {
            font-size: 72px;
            font-weight: bold;
            text-align: center;
            border: 1px solid black;
            padding: 20px;
        }
        #start {
            margin-top: 20px;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
</head>
<body>
    <div id="number">0</div>
    <button id="start">Start</button>

    <script type="text/javascript">
        let number = 0;

        document.getElementById('start').addEventListener('click', function() {
            gsap.to("#number", {
                duration: 2,
                innerHTML: 100,
                roundProps: "innerHTML",
                ease: "power1.out",
                onUpdate: () => {
                    number = parseInt(document.getElementById("number").innerHTML);
                },
                onUpdateParams: ["{self}"]
            });
        });

        document.getElementById('start').addEventListener('click', function() {
            document.getElementById("number").innerHTML = 0;
            gsap.to("#number", {
                duration: 2,
                innerHTML: 100,
                roundProps: "innerHTML",
                ease: "power1.out",
                onUpdate: () => {
                    number = parseInt(document.getElementById("number").innerHTML);
                },
                onUpdateParams: ["{self}"]
            });
        });
    </script>
</body>
</html>

In the example code above, when you click the button, the text inside the div element is animated using the GSAP animation library. It smoothly changes from its current value to 100 over a span of 2 seconds.

If you click the button again, the text inside the div element resets to 0, and the animation starts over. This animation displays each number incrementally, creating a visually appealing effect.

Here’s the output:

Conclusion

In conclusion, this article explores different methods and techniques to animate number increases in JavaScript.

It covers using setInterval for regular updates, requestAnimationFrame for smoother animations, and JavaScript animation libraries like GSAP.

These methods provide programmers or developers with options to create engaging number animations in their web projects.

We are hoping that this article provides you with enough information that helps you understand the JavaScript animate number increase.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment