Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

49. 举一个 web worker 的例子 #66

Open
webVueBlog opened this issue Jun 9, 2022 · 0 comments
Open

49. 举一个 web worker 的例子 #66

webVueBlog opened this issue Jun 9, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

您需要按照以下步骤开始使用网络工作者进行计数示例

创建一个 Web Worker 文件:您需要编写一个脚本来增加计数值。我们将其命名为 counter.js

let i = 0;

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

timedCount();

这里 postMessage() 方法用于将消息回传到 HTML 页面

创建 Web Worker 对象:您可以通过检查浏览器支持来创建 Web Worker 对象。让我们将此文件命名为 web_worker_example.js

if (typeof w == "undefined") {
  w = new Worker("counter.js");
}

我们可以接收来自 web worker 的消息

w.onmessage = function (event) {
  document.getElementById("message").innerHTML = event.data;
};

终止 Web Worker:Web Worker 将继续侦听消息(即使在外部脚本完成后),直到它被终止。您可以使用 terminate() 方法来终止侦听消息。

w.terminate();

重用 Web Worker:如果将 worker 变量设置为 undefined,则可以重用代码

w = undefined;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant