简体   繁体   English

JS:网络工作者不工作

[英]JS : Web Workers don't work

I'm doing a code but it looks like to don't work, what's wrong here : 我正在编写代码,但似乎无法正常工作,这里出了什么问题:

HTML : HTML

<div>
    <button onclick="startWorkerp3()">Start Worker</button> 
    <button onclick="stopWorkerp3()">Stop Worker</button>
    <img id="p_3" src="PROBLEM3.png" style="display: none;">
    <output id="p3"></output>
</div>

JS: JS:

<script>
        var w;

        function startWorkerp3() {
            if(typeof(Worker) !== "undefined") {
                if(typeof(w) == "undefined") {
                    w = new Worker("p3.js");
                }
                w.onmessage = function(event) {
                    document.getElementById("p3").innerHTML = event.data;
                };
            } else {
                document.getElementById("p3").innerHTML = "Sorry! No Web Worker support.";
            }
        }

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

        function isPrime(value) {
            for(var i = 2; i < value; i++) {
                if(value % i === 0) {
                    return false;
                }
            }
            return value > 1;
        }
</script>

p3.js p3.js

function problem3(){
    var img = document.getElementById('p_3');
    img.style.display = img.style.display === 'block' ? 'none' : 'block';
    var number=1+e9;
    for(var i=2;i<number;i++){
        if(isPrime(i) && number%i==0)
            var maxPrime = i;
    }
    postMessage(maxPrime);
}

The output is nothing : 输出为空:

在此处输入图片说明

I load p551 and it works normally,now I'm trying to use on p3.js a WebWorker to take it on without browser error , that asks u if u want to wait or terminate it. 我加载了p551,它可以正常工作,现在我正尝试在p3.js上使用WebWorker来进行加载,而不会出现浏览器错误 ,询问您是否要等待或终止它。 But I think the code is write in a right syntax, so what's wrong? 但是我认为代码是用正确的语法编写的,那么怎么了?

As web workers can't interact with the DOM, the idea here would be to handle all the computations in the web worker (ie p3.js) and the display updates should be handled on the other side, as they are locked in the UI thread, no matter what we do (afaik anyways). 由于Web Worker无法与DOM交互,因此此处的想法是处理Web Worker中的所有计算(即p3.js),并且显示更新应在另一侧处理,因为它们已锁定在UI中线程,无论我们做什么(仍然是afaik)。

isPrime would probably be relocated in p3.js as window is not available in the context of a worker. isPrime可能会在p3.js搬迁的window是不是在一个工人的情况下可用。

A few things are broken in your code. 您的代码中有些问题。 Also you probably don't want to test with such a high value as 1e9 to find prime number with a non optimized algorithm, it might look like an irrelevant thing to say but when you want to test that something works, I'd suggest not going too crazy with the "siders" :D 另外,您可能不想使用非优化算法来查找1e9这样的高值来查找素数,这似乎是无关紧要的事情,但是当您要测试某些东西有效时,我建议您不要和“ siders”太疯狂了:D

So first things first, let's get rid of the DOM api call on the worker side. 首先,让我们摆脱工作人员端的DOM api调用。 (note that I replaced 1+e9 with +1e9 ) (请注意,我用+1e9代替了1+e9

function problem3(){
    var number = +1e9;
    for(var i=2;i<number;i++){
        if(isPrime(i) && number%i==0)
            var maxPrime = i;
    }
    postMessage(maxPrime);
}

Now, since p3.js is a different file in a different thread, you won't have access to any of the memory of your main script. 现在,由于p3.js是位于不同线程中的另一个文件,因此您将无权访问主脚本的任何内存。 Which means that isPrime is unavailable in the worker's context. 这意味着isPrime在工作人员的上下文中不可用。 Hopefully this has a straight forward solution as you can simply move the isPrime function to p3.js. 希望这有,你可以简单地移动一个直接的解决方案isPrime功能p3.js.

You are using onclick="startWorkerp3()" to attach your user control. 您正在使用onclick="startWorkerp3()"来附加用户控件。 It is generally recommended to user addEventListener , and in this particular case your worker will never start because of onclick 's context handling 通常建议用户使用addEventListener ,在这种情况下,由于onclick的上下文处理,您的工作程序将永远无法启动

As an alternative, for instance it could look like this 作为替代,例如,它可能看起来像这样

<button id="start">Start Worker</button>

And in the main script file we need to relocate the code that was removed from the worker. 并且在主脚本文件中,我们需要重新定位从工作程序中删除的代码。 From what I understand, you want to toggle the image visibility when your computation is sarted/over. 据我了解,您想在计算结束/结束时切换图像的可见性。

document.querySelector('#start').addEventListener('click', function () {
    document.getElementById('p_3').style.display = 'none';
    startWorkerp3();
});

And when the worker has finished computing 当工人完成计算后

w.onmessage = function(event) {
    document.getElementById("p3").innerHTML = event.data;
    document.getElementById("p_3").style.display = 'block';
};

In the end here is how it could like (I'm summing up so that you can copy/paste and test it easily). 最后是它的样子(我在总结一下,以便您可以轻松地复制/粘贴和测试它)。 You will probably spot some little tweaks that I made, some of them can be ignored, anyways it would have been too long to explain every little thing. 您可能会发现我所做的一些小调整,其中一些可以忽略,反正解释每个小事情的时间都太长了。

HTML 的HTML

<div>
    <button id="start">Start Worker</button>
    <button id="stop">Stop Worker</button>
    <img id="p_3" src="PROBLEM3.png" alt="PROBLEM3.png" style="display: none;">
    <output id="p3"></output>
</div>

JS JS

    var w;

    document.querySelector('#start').addEventListener('click', function () {

        var img = document.getElementById('p_3');
        img.style.display = 'none';

        startWorkerp3();
    });

    document.querySelector('#stop').addEventListener('click', function () {
        if (w) {
            stopWorkerp3();
        }
    });


    function startWorkerp3() {
        if(typeof(Worker) !== "undefined") {
            if(typeof(w) == "undefined") {
                w = new Worker("p3.js");
            }
            w.onmessage = function(event) {
                document.getElementById("p3").innerHTML = event.data;
                document.getElementById('p_3').style.display = 'block';
            };
        } else {
            document.getElementById("p3").innerHTML = "Sorry! No Web Worker support.";
        }

        w.postMessage('start');
    }


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

p3.js p3.js

onmessage = function (evt) {
    postMessage(problem3());
};


function problem3() {
    var number=100000;
    for(var i=2;i<number;i++){
        if(number%i==0 && isPrime(i))
            var maxPrime = i;
    }

    return maxPrime;
}


function isPrime(value) {
    for(var i = 2; i < value; i++) {
        if(value % i === 0) {
            return false;
        }
    }
    return value > 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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