终止Web工作者

时间:2013-05-14 15:39:59

标签: javascript web-worker

我有这个网络工作者将一些段落添加到div中,就像这样

var worker1 = new Worker('many.js');
var worker2 = new Worker('many.js');
var worker3 = new Worker('many.js');
var worker4 = new Worker('many.js');

      worker1.onmessage = function (event) {
      function xx(){$(event.data).appendTo('#div_1');}
      setInterval(xx,4000);
      }; 

      worker2.onmessage = function (event) {
      function xx(){$(event.data).appendTo('#div_2');}
      setInterval(xx,4400);
      };


      function killworker(){
      worker1.terminate();
      }

这是many.js文件

function j()
{return "<p>lorem ispum</p>"}

postMessage(j());

我能够像这样摧毁工人

worker1.terminate();

但是我希望将它包装在一个函数中并尝试在按钮点击事件后终止它

<button onClick="javascript:killworker();">stop worker</button>

我的代码似乎没有终止worker。为什么它不起作用?。

2 个答案:

答案 0 :(得分:0)

您的killworker函数是否在更广泛的背景下定义?如果是,那就是你的问题。请尝试使用window.killworker = function() { }而不是function killworkers() {}来明确地将您的函数定义为可从任何范围访问的全局函数。

答案 1 :(得分:0)

我必须首先清除InterInterval

我的代码现在看起来像

var worker1 = new Worker('many.js');
var worker2 = new Worker('many.js');
var worker3 = new Worker('many.js');
var worker4 = new Worker('many.js');

      var timer = 0;

      worker1.onmessage = function (event) {
      function xx(){$(event.data).appendTo('#div_1');}
      timer = setInterval(xx,2000);
      }; 

       function killworker(){
       clearInterval(timer);
      worker1.terminate();
      }

      worker2.onmessage = function (event) {
      function xx(){$(event.data).appendTo('#div_2');}
      setInterval(xx,2200);
      };

我的按钮<button onclick="killworker()">stop worker</button>