skip to Main Content

I would like to display a counter on a web page who display all numbers one by one
I wrote this code, but it doesn’t work, it displays only the last number

Can you help me? ChatGPT was useless :))

<!DOCTYPE html>
<html>
<head>
    <title>Compteur de 1 à 1000000</title>
</head>
<body>
<div id="counter"></div>
<script>
    const counterElement = document.getElementById('counter');

    for (let i = 1; i <= 1000000; i++) {
        counterElement.innerHTML = i;
    }

</script>
</body>
</html>

2

Answers


  1. The easiest way would be to make your code async by wrapping it in such a function and then adding a delay inside your for loop, like this:

    // `async` basically tells the engine that when it encounters `await` inside here,
    // it needs to suspend the method. It also forces the return value to be
    // a `Promise`, which you can, in turn, await itself if necessary.
    async function counter(){
    
        for (let i = 1; i <= 100; i++) {
        
            counterElement.innerHTML = i;
            
            // The loop will be suspended until this promise resolves,
            // which will be in 100ms, as it awaits the completion of the timeout
            // the timeout calls the `resolve` callback, ending the timer
            await new Promise(r => setTimeout( r, 100 ));
            
        }
        
    }
    
    const counterElement = document.getElementById('counter');
    
    // Since this is now async, we can hook into this as well
    // When the counter has completed, we will print the text below.
    counter().then(() => {
      
      counterElement.innerHTML = `Counter Complete`;
      
    });
    html, body {
      height:100%;
    }
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      font-variant: numeric-tabs;
      font-size: 4em;
    }
    <div id="counter"></div>
    Login or Signup to reply.
  2. It is likely happening too fast for you to discern the counter. If you include a setTimeout (or something similar) you will see the numbers count up. Perhaps something like this:

    const counterElement = document.getElementById('counter');
    
    function delay(element, value, step, maxValue, duration) {
        if (value <= maxValue) {
            element.innerHTML = value;
            setTimeout(() => {
                value += step;
                delay(element, value, step, maxValue, duration);
            }, duration);
        }
    }
    
    delay(counterElement, 0, 10, 1000, 100);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search