I want to add progress indication with CPU-bound processing

Asked 1 years ago, Updated 1 years ago, 385 views

There's a CPU-bound for loop, so I'd like to add something like a progress indication there

Even if you insert DOM operations in the middle, the display will not be updated until all of them are finished

Separate the processing into a trailing recursive function and insert setTimeout and so on
I think we can do it if we interrupt the event loop.
I will have to change the program a lot, so
Is there any way to update the screen that you can just insert the for statement?

constfib=n=>n<=1?n:fib(n-1)+fib(n-2);

construction= document.getElementById('msg');
for(leti=1;i<=40;i++){
  const msg = `fib(${i}) = ${fib(i)}`;
  console.log(msg);
  element.value = msg;
}
<input id="msg" type="text"></input>

javascript

2022-10-26 00:00

1 Answers

If you write the wait action within the asynchronous function declared by async, the screen will be updated.
I have specified 250 ms so that I can follow setTimeout with my eyes.
You will actually wait for the function to run, such as Promise.resolve.

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/async_function

<input id="msg" type="text">/input>
<script type="text/javascript">
  constfib=n=>n<=1?n:fib(n-1)+fib(n-2);

  (async() = > {
    construction= document.getElementById('msg');
    for(leti=1;i<=40;i++){
      const msg = `fib(${i}) = ${fib(i)}`;
      console.log(msg);
      element.value = msg;
      wait new Promise(s=>setTimeout(s,250));
    }
  })();
</script>


2022-10-26 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.