How to force real-time display updates in javascript?
P粉148434742
P粉148434742 2023-09-04 17:44:30
0
1
411

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 display.innerHTML = i; with?

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粉148434742
P粉148434742

reply all (1)
P粉369196603

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();


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; };
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!