Simple to understand Web Workers API

1. Why use the Web Workers API

By using the API, web applications can be independent of the main thread, runs a separate thread to process the script.

Longer time-consuming tasks can be solved in a separate thread to avoid blocking the main thread.

2. Applications

Worker.js 1. Create a new file, the lengthy code into js wherein; communicate data via postMessage

// worker.js
let sum = 0;
for(let i=0; i<1000000; i++) {
   sum += i;
}
self.postMessage (SUM); // Self represents the current window

2. Create a new instance of Worker

worker = const new new the Worker ( './ worker.js'); // pass a file 
worker.onmessage = function (E) {
    // e.data acquired data transmission 
}

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/11854194.html