网络辅助角色不工作

Web Worker not working

本文关键字:工作 角色 网络辅助      更新时间:2023-09-26

我是HTML5的新手。我最近学习了HTML5的基础知识,但是当我使用HTML5进行中级编码时,我想出了一个名为"HTML5 Web Workers"的东西。我用它写了一个简单的程序,但它不起作用。

我的HTML5代码:

<html>
    <head>
        <title>HTML5 - Web Workers</title>
    </head>
    <body>
        <p>Count : <output id="result"></output></p>
        <button onclick="startWorker()">Start count</button>
        <button onclick="endWorker()">End count</button>
        <script>
        var w; //the variable of object for web worker
        function startWorker() {
            if(typeof(Worker)!="undefined") //checking if browser supports web worker
            {
                if(typeof(w)=="undefined")
                {
                    w = new Worker("counter.js");
                }
                w.onmessage = function(e)
                {
                    document.getElementById('result').innerHTML = e.data;
                };
            }
            else
            {
                document.getElementById('result').innerHTML = "Your browser doesnot support HTML5 Web Worker! :)"; // or display the message that web worker is not supported!
            }
        }
        function endWorker() {
            w.terminate();
        }
        </script>
    </body>
</html>

我的网络辅助角色文件:

var i=0;
function timedCount() {
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()", 500);
}
timedCount();

你能告诉我为什么它不起作用吗?

你的代码对我来说很好用。您使用的是哪种浏览器,在错误控制台中遇到了哪个错误?

如果您使用的是 Chrome 并且正在从本地文件系统进行测试(即您尚未将文件上传到网络服务器(,则必须在启动浏览器时添加一个特殊标志。您必须使用chrome --allow-file-access-from-files启动Chrome,这基本上允许您从本地文件系统上的脚本创建工作线程。但是,如果您将文件上传到Web服务器并使用这些文件进行测试 - 则不需要此标志。