P粉3691966032023-09-05 10:50:29
requestAnimationFrame
method
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>
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; };