2013-02-19 147 views
1

我是新來的HTML5。我最近瀏覽了HTML5的基礎知識,但是當我使用HTML5進行中級編碼時,我想出了一個名爲「HTML5 Web Workers」的東西。我用它寫了一個簡單的程序,但它不起作用。Web工作不工作

我的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> 

我的Web工作文件:

var i=0; 

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

timedCount(); 

你能告訴我,爲什麼它不工作?

+2

在哪裏'的postMessage()'?什麼不工作,你期望會發生什麼?控制檯中有任何錯誤? – JJJ 2013-02-19 09:21:04

+2

@Juhana,postMessage()是一個預定義的函數! – 2013-02-19 09:27:46

+0

好的。什麼不工作,你期望會發生什麼?控制檯中有任何錯誤? – JJJ 2013-02-19 09:29:14

回答

8

您的代碼爲我工作得很好。您正在使用哪個瀏覽器以及您在錯誤控制檯中遇到哪個錯誤?

如果您使用的是Chrome,並從本地文件系統正在測試(即你沒有上傳文件到Web服務器),那麼你必須在啓動瀏覽器時添加一個特殊的標誌。您必須使用chrome --allow-file-access-from-files啓動Chrome,它基本上允許您從本地文件系統上的腳本創建工作人員。但是,如果您將文件上傳到網絡服務器並使用這些文件進行測試 - 則不需要此標誌。

+1

是的!謝謝:D我用localhost開始它,它只是工作正常:) – 2013-02-19 09:47:41