简体   繁体   中英

Is there any way to force repaint of DOM element inside javascript loop?

Here is a simplified example of a problem I am trying to solve.

I have a javascript loop and on each iteration, I ask for some input from the user and then want to display it in the browser during the the next iteration. Currently it saves up all repaint operations to the end of the script and then processes them in a block. Is there a way to force a refresh/repaint in the browser while the loop is in progress?

Here's the code.

<html>

  <head>
    <script>
      function mirror() {
        var userText = "Your text will go here";

        do {
          document.getElementById("target").innerHTML += userText + "<br>";
          userText = prompt("Enter your text, or click Cancel to finish");
        }
        while (userText !== null);
      }

    </script>
  </head>

  <body onload="mirror()">
    <p id="target"></p>
  </body>

</html>

The normal recommendation for browser repaint is to use window.setTimeout() however this is not working within the loop.

The synchronous blocking while is the problem - until the current Javascript stops running and yields to let the browser handle other stuff (like repainting), no repainting will occur.

You might add a slight asynchronous delay inside the loop - after setting the innerHTML , wait for 50ms before continuing:

 const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); async function mirror() { var userText = "Your text will go here"; do { document.getElementById("target").innerHTML += userText + "<br>"; await delay(50); userText = prompt("Enter your text, or click Cancel to finish"); } while (userText !== null); } mirror();
 <p id="target"></p>

That said, this is somewhat of an X/Y problem. It would be better to avoid prompt entirely - it blocks rendering (resulting in problems like these) and is somewhat user-unfriendly. Consider creating a proper modal input instead, and then you can create the logic you need without blocking the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM