Search code examples
javascriptinnerhtmlpartial-page-refresh

JavaScript. a loop with innerHTML is not updating during loop execution


I'm trying to refresh a div from Javascript at each loop and see 1, 2, 3, .... The following code works, but only displays the final result (9998). How is it possible to display all the steps? Thank you in advance.

<html>
<head>
</head>
<body>

<div id="cadre" style="width=100%;height=100%;">
    <input type="button" value="Executer" onclick="launch();"/>
    <div id="result" ></div>
</div>

<script type="text/javascript">
     function launch(){
        for (inc=0;inc<9999;inc++){
            document.getElementById('result').innerHTML = inc;
        }
     }
</script>

</body>
</html>

Solution

  • var i = 0;
    
    function launch(){
               var timer = window.setInterval(function(){
                   if( i == 9999 ){
                       window.clearInterval( timer );
                   }
                   document.getElementById('result').innerHTML = i++;
               }, 100);
    }
    
    launch();