1

我有这个网络工作者,它将一些段落附加到一个 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>

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

4

2 回答 2

0

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

于 2013-05-14T15:44:37.767 回答
0

我必须先清除Interval

我的代码现在看起来像

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>

于 2013-05-14T16:17:18.820 回答