Js is a single-threaded scripting language, and the new Worker in H5 enables JS to achieve multi-threading.

You can first check whether the tourist has registered the Worker.

if(typeof(Worker)! = ="undefined") {/ / worker support
}else{
    / / Worker does not support
}
Copy the code

To create the Worker instance object, you need to pass in the js file path running in the background.

var worker=new Worker("Js file path");
Copy the code

Worker threads can send data to the main thread via postMessage.

postMessage(data);
Copy the code

The main thread can listen to messages to receive data.

worker.onmessage=function(){
    console.log(event.data);
}
Copy the code

4. Terminate the Worker

worker.terminate();
Copy the code

Note that postMessage consumes resources and causes no response on the page. Therefore, the worker is suitable for background operation, but should not communicate with the caller frequently