How to force real-time display updates in javascript?
P粉148434742
2023-09-04 17:44:30
<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>
requestAnimationFrame
methodUse requestAnimationFrame or setTimeout when exiting the loop to allow the UI to be updated, then resume the loop from where it left off.
Web Worker method
Put your algorithm into a JS file and a message will be posted when it needs to be updated
and in your UI code.