网络工作者JavaScript

时间:2018-10-27 10:23:21

标签: javascript web-worker

我必须为需要网络工作者的学校做项目,该项目是关于必须在后台计算的质数,但是我具有计算质数的功能,但我不知道如何正确使用它(网络工作者)与主要功能,我也得到一些错误:

index.html:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Prvocisla</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
    <script src="script.js"></script>
</head>
<body>
    <p>Count numbers: <output id="result"></output></p>
    <button onclick="startWorker()">Start Worker</button> 
    <button onclick="stopWorker()">Stop Worker</button>
</body>
</html>

script.js:

var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("prvocisla.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Web workery nie su dostupne!";
    }
}

function stopWorker() { 
    w.terminate();
    w = undefined;
}

prvocisla.js:

function jePrvocislo(cislo){
    var i = 2;
    while(i < cislo){
        if(cislo % i == 0){
            return false;
        }
        i++;
    }
    return true;
}

function najdiPrvocislo(cislo){
    var i = 0;
    while(i < cislo){
        if(jePrvocislo(i)){
            console.log(i);
        }
        i++;
    }
}

najdiPrvocislo(50000);

错误: Errors

引起错误的行:

w = new Worker("prvocisla.js");
<button onclick="startWorker()">Start Worker</button> 

0 个答案:

没有答案