简体   繁体   中英

Web worker usage for checking prime in html5

I am new to this web worker concept, for problem description

  • Take a number input (less than 100) from the user and save it to the web storage.
  • Create a web worker to increment the number until it becomes prime.
  • Provide two buttons of 'Start' and 'End' to start or end the process.
  • Upon pressing 'end', the increment stops, or the number becomes prime – whichever occurs first.

But in the below code, checkprime function is not working, please assist. I coded below in HTML:

<form>
  <input id="num" type="number" max="100" /></br><br/><br/>
  <center>
    <p> Result<output id="result"></output></p>
    <button onclick="CheckPrime()">Start</button>
    <button onclick="StopProcess()">Stop</button>
  </center>
</form>
var w;

function CheckPrime() {
  sessionStorage.inputNum = document.getElementById("num").value;

  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {

      w = new Worker("web.js");

    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    }
  } else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
  }
}

function StopProcess() {
  alert("Process has been ended");
  w.terminate();
  w = undefined;
}

webworker.js

function p() {
  var i;
  n = sessionStorage.inputNum;
  for (i = 2; i <= n - 1; i++) {
    if (n % i == 0) {
      n++;
    }
  }
  postMessage("found prime" + n);

}
p();

Web Workers can't access Storage objects (neither SessionStorage nor LocalStorage). The closest thing available is IndexedDB but in your case it's not recommended at all.

Instead just make your worker wait for a message event from the main context:

in main

  w = new Worker("web.js");
  w.postMessage(+document.getElementById("num").value);

in worker.js

self.onmessage = function p( evt ) {
  var i;
  var n = evt.data;
  for (i = 2; i <= n - 1; i++) {
    if (n % i == 0) {
      n++;
    }
  }
  postMessage("found prime" + n);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM