How can I get javascript to update my webpage in real-time?
It seems that my Chrome browser puts all of its processing effort into required computations, and then does the webpage updates. Below is the simplest test HTML file. I would prefer to see sequential counting (instead of just one jump to the final value). What should I replace display.innerHTML = i;
with?
I hope the answer is not to break up my computation into many computations using setInterval or something like that. Of course, the breaks this creates will allow display updates, but I prefer not to manage it in such detail…I am hoping that there is a "blocking" display function available, so that the count here will not proceed until the browser renders my display update (or is there is a "flush" command like C provides?). I could use the developer console if needed, but that is also not ideal.
<!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>
2
Answers
requestAnimationFrame
wayUsing requestAnimationFrame or setTimeout where you exit the loop to let it allow the UI to be updated and you resume the loop where you left off.
The web worker way
Put your algorithm in a JS file where it posts a message when it wants an update
and in your UI code.
As @epascarello mentioned in a comment, using a worker is the conventional way to handle computational tasks off of the main thread — in order to prevent blocking renders. Below is a simple example that you can use to reproduce.