Javascript loop with innerHTML is not updated during loop execution

I am trying to update a div from Javascript in every loop and see 1, 2, 3, .... The following code works, but only displays the final result (9998). How can all stages be displayed? 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>
+5
source share
3 answers
var i = 0;

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

launch();
-2
source

JavaScript , , . (, for, , , .)

setTimeout() setInterval() ( window). , ; , . , "", .

, :

function launch() {
   var inc = 0,
       max = 9999;
       delay = 100; // 100 milliseconds

   function timeoutLoop() {
      document.getElementById('result').innerHTML = inc;
      if (++inc < max)
         setTimeout(timeoutLoop, delay);
   }

   setTimeout(timeoutLoop, delay);
}

, timeoutLoop() setTimeout() - .

setTimeout() setInterval() , , clearTimeout() clearInterval(), - , , :

function launch() {
   var inc = 0,
       max = 9999;
       delay = 100; // 100 milliseconds

   var iID = setInterval(function() {
                            document.getElementById('result').innerHTML = inc;
                            if (++inc >= max)
                               clearInterval(iID);
                         },
                         delay);
}

, delay . , inc , , , launch(): .

+18

Try

document.getElementById('result').innerHTML += inc;
-1

All Articles