king0 liam
king0 liam

Reputation: 11

how to make progressBar work during long loops of computing?

how to make progressBar work during long-time loops of computing? by using setInterval()? by using async or await? how? please show me in code. I know using VUE's bind can help,but I want simple js-code without any outside import to do this.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style type="text/css">
      #myProgress {
        width: 100%;
        background-color: #ddd;
      }

      #myBar {
        width: 10%;
        height: 30px;
        background-color: #4caf50;
        text-align: center;
        line-height: 30px;
        color: white;
      }
    </style>
  </head>

  <body>
    <div style="text-align: center">
      <h2>RSA!</h2>
      <div id="myProgress">
        <div id="myBar">10%</div>
      </div>
      <br />
      <label>输入素数的范围,最大:21474836:</label>
      <input
        type="number"
        id="myCount"
        placeholder=""
        value="2147483"
        min="100"
        max="21474836"
      />
      <button class="dom1" onclick="initPrim()">1.素数生成器</button><br />
      <div
        id="result0"
        style="width: 100%; word-break: break-all; word-wrap: break-word"
      ></div>
      <br />
    </div>
  </body>
  <!--21474836  2147483647 sqrt(Integer.MAX)=46341-->
  <script>
    var PrimeArray = [2];
    //initPrim 生成素数表
    async function initPrim(limit) {
      document.getElementById("result0").innerHTML = " ";
      var count = document.getElementById("myCount").value;
      for (i = 2; i < count; i++) {
        let j;
        let tag = 0;
        for (
          j = 0;
          j < PrimeArray.length && PrimeArray[j] < Math.sqrt(i) + 1;
          j++
        ) {
          if (i % PrimeArray[j] == 0) {
            tag = 1;
            break;
          }
        }
        if (tag == 0) {
          PrimeArray.push(i);
        }
      }
      document.getElementById("result0").append("p=\t" + PrimeArray);
    }
  </script>
</html>

Upvotes: 0

Views: 52

Answers (1)

king0 liam
king0 liam

Reputation: 11

HTML Web Workers is the solution that I need. Question closed! https://www.w3schools.com/HTML/html5_webworkers.asp

Upvotes: 1

Related Questions