Home  >  Q&A  >  body text

How to force real-time display updates in javascript?

<p>How do I get the javascript to update my webpage in real time? It seems like my Chrome browser is putting all the processing work into the calculations required and then updating the web page. Below is the simplest test HTML file. I'd rather see sequential counting (rather than just jumping to the final value). What should I replace <code>display.innerHTML = i;</code> with? </p> <p>I hope the answer is not to use setInterval or something similar to break my calculation into many calculations. Of course the interrupt this creates will allow the display to update, but I don't like managing it in such detail... I wish there was a "block" display feature available so that the counting here doesn't continue until the browser Rendering my display updates (or is there a "refresh" command like C provides?). I can use the developer console if needed, but that's not ideal either. </p> <pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html> <body> <p id="Display"></p> <script> const display = document.getElementById("Display"); for (let i = 0; i <= 3000000000; i ) { if (i % 100000000 == 0) display.innerHTML = i; } </script> </body> </html></pre></p>
P粉148434742P粉148434742411 days ago503

reply all(1)I'll reply

  • P粉369196603

    P粉3691966032023-09-05 10:50:29

    requestAnimationFramemethod

    Use requestAnimationFrame or setTimeout when exiting the loop to allow the UI to be updated, then resume the loop from where it left off.

    const display = document.getElementById("Display");
    
    function process() {
    
      let index = 0;
      const max = 3000000000;
      
      function run () { 
        while (index <= max) {
          if (index % 100000000 == 0) {
            display.innerHTML = index;
            break;
          }
          index++;
        }
        if (index++ <= max) window.requestAnimationFrame(run);
      }
      
      run();
    }
    
    process();
    <p id="Display"></p>


    Web Worker method

    Put your algorithm into a JS file and a message will be posted when it needs to be updated

    for (let i = 0; i <= 3000000000; i++) {
        if (i %   100000000 == 0) self.postMessage(i);
    }
    

    and in your UI code.

    const display  = document.getElementById("Display");
    const myWorker = new Worker("workerAlgorithm.js");
    myWorker.onmessage = (e) => {
      display.innerHTML = e.data;
    };
    

    reply
    0
  • Cancelreply