Web Workers: Execute the specified script on a background thread

With Web Workers you can run JavaScript in a background thread, where the thread can perform tasks without interfering with the user interface.

rules of use

  • workeris to use Worker()the constructed instance object to run a named JavaScript script in a background thread.
  • workerAn instance object can be created by sending information to the JavaScript code that created it.
  • workerRuns in another global context, not an windowobject.
  • workerDOM nodes cannot be manipulated directly, nor can windowthe default methods and properties of objects be used.
  • workerpostMessage()Between the main thread and the main thread, the respective data is sent through the method, and the onmessageevent handler is used to respond to the data, and the data is in the properties of the messageevent .data
  • workerThe data passed to and from the main thread is additionally copied data.
  • The main thread can terminate()terminate the instance immediately using methods on the instance object worker.
  • workerInternally a thread can use to close()close itself.
  • workerOne of the advantages is the ability to perform processor-intensive operations without blocking the UI thread.

Application examples

As shown in the following code, the compatibility check is first performed in the main thread, creating an worker.jsexecuted by Worker. By myWorker.postMessage()sending a message. The message returned by the myWorker.onmessageresponse .Worker

const a = 1;
const b = 2;

if (window.Worker) {
  const myWorker = new Worker('./worker.js');
  myWorker.postMessage({ a, b });

  myWorker.onmessage = e => {
    console.log('收到worker的信息...');
    console.log(e.data);
  };
}
复制代码

In Worker, by onmessageresponding to the message sent by the main thread, after some processing, by postMessagereturning the message to the main thread.

// worker.js
onmessage = e => {
  console.log('收到主线程的信息...');
  const { a, b } = e.data;
  const sum = a + b;
  postMessage(sum);
};
复制代码

From here we can see that in the main thread, onmessageand postMessage()must hang on the workerobject. And workerinternally, it doesn't have to, because it workerhas its own scope.

如下代码所示,在workeronmessage中打印this

onmessage = e => {
  console.log(this);
};
复制代码

image-20220411142557425

终止 worker

在上述代码中,若在主线程中调用myWorker.terminate(),则不会收到任何消息,因为worker线程刚创建完毕就被终止。

const a = 1;
const b = 2;

if (window.Worker) {
  const myWorker = new Worker('./worker.js');
  myWorker.postMessage({ a, b });
  // 终止myWorker
  myWorker.terminate();

  myWorker.onmessage = e => {
    console.log('收到worker的信息...');
    console.log(e.data);
  };
}
复制代码

同样,在worker线程中调用close(),主线程也不会有任何响应,因为线程刚启动就被关闭。

close();

onmessage = e => {
  console.log('收到主线程的信息...');
  const { a, b } = e.data;
  const sum = a + b;
  postMessage(sum);
};
复制代码

共享 worker

主线程:

const a = 1;
const b = 2;

if (window.Worker) {
  const myWorker = new SharedWorker('./worker.js');
  myWorker.port.postMessage({ a, b });

  myWorker.port.onmessage = e => {
    console.log('收到worker的信息...');
    console.log(e.data);
  };
}
复制代码

worker线程:

onconnect = e => {
  const port = e.ports[0];

  port.onmessage = e => {
    const { a, b } = e.data;
    const sum = a + b;
    port.postMessage(sum);
  };
};
复制代码

参考:

Guess you like

Origin juejin.im/post/7085238473942106126