You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"<p>message from the background thread: " + event.data + "</p>";
319
+
};
320
+
321
+
下面展示了一个做1亿次简单的数学运算的web worker:
322
+
323
+
var end = 1e8, tmp = 1;
324
+
325
+
postMessage('hello there');
326
+
327
+
while (end) {
328
+
end -= 1;
329
+
tmp += end;
330
+
if (end === 5e7) { // 5e7 is the half of 1e8
331
+
postMessage('halfway there, `tmp` is now ' + tmp);
332
+
}
333
+
}
334
+
335
+
postMessage('all done');
336
+
337
+
web worker使用postMessage()来和调用它的程序通讯,调用者通过onmessage事件来接受更新。onmessage事件处理函数接受一个事件对象作为参数,这个对象含有一个由web worker传过来data属性。类似的,调用者(在这个例子中)也可以使用ww.postMessage()来给web worker传递数据,web worker可以通过一个onmessage事件处理函数来接受这些数据。
338
+
339
+
上面的例子会在浏览器中打印出:
340
+
341
+
message from the background thread: hello there
342
+
message from the background thread: halfway there, `tmp` is now 3749999975000001 message from the background thread: all done
0 commit comments