This is my first article on getting started.

I. Introduction to Worker threads Web Worker

The JavaScript language uses a single-threaded model, which means that you can’t delegate work to separate threads or processes like you can in multithreaded languages. That is, all tasks are done in one thread. To put it simply, Web workers can make JS “multithreaded”. Of course, Webworker does not change the nature of js single thread. Webworker multi-threading refers to browser multi-threading, because browsers can provide multiple INSTANCES of JS engine, each instance can run the corresponding program independently, but in each INSTANCE of JS engine, JS scripts are still executed in a single thread. Each instance is equivalent to a Webworker.

How to use it?

The main thread uses the new command to create a Worker thread.

let worker = new Worker('worker.js');
Copy the code

The argument Worker() receives is a JS file, which is the task the Worker thread needs to process. Since the Worker cannot read local files, the script must come from the network.

The main thread calls the worker.postMessage() method to send a message to the worker.

worker.postMessage('webworker');
worker.postMessage({fn: 'worker', data: ['Worker']});
Copy the code

The argument to the worker.postmessage () method is the data that the main thread passes to the worker. The main thread can specify a listener via worker. onMessage to receive messages from child threads.

Worker.onmessage = (event) => {console.log(' received message from child thread '+ event.data); foo(); } function foo() {worker.postmessage (' finished '); }Copy the code

The data attribute of the Event object can obtain the data sent by the Worker.

  • Worker thread

    Worker threads need to have a listener function inside that listens for message events.

Self. addEventListener('message', function (e) {self.postMessage(' message: '+ e.data); }, false);Copy the code

The code above is the child thread itself, and self.postMessage can pass messages to the main thread.

  • Worker loading script

The Worker can use importScripts()

importScripts('worker1.js'); // Also supports multiple scripts importScripts('worker1.js','worker2.js');Copy the code
  • Monitoring error
worker.addEventListener('error',(event)=>{
    // ...
})
Copy the code
  • Close the Worker

Once a Worker thread is successfully created, it will always be running, which makes it easier to respond to the main thread at any time.

After use, the Worker must be shut down to save system resources.

Three, for example,

Let’s say we have some very time-consuming operations that don’t affect the running of the page, then we can think of using webworker. Let’s take a look at how long it takes to execute Fibonacci without using the thread webWorker.

function Fib1(n) { if (n == 1 || n == 2) { return 1; } return Fib1(n - 1) + Fib1(n - 2); } console.time(' execute time '); Fib1(43) console.timeEnd(' execution time ');Copy the code



That’s how long it takes to execute Fibonacci once, about four seconds. Let’s see how long it takes to execute three times.

function Fib1(n) { if (n == 1 || n == 2) { return 1; } return Fib1(n - 1) + Fib1(n - 2); } console.time(' execute time '); Fib1(43) Fib1(43) Fib1(43) console.timeEnd(' Execution time ');Copy the code



You can see that three Fibonacci sequences are executed in about 10 seconds. So let’s havewebworkerAppearance.

  • Main thread code
let worker = new Worker('workerjs_1.js');
let worker = new Worker('workerjs_2.js');
let worker = new Worker('workerjs_3.js');
worker.onmessage =  (event) => {
    //...
}
Copy the code
  • Worke threads (note that scripts must originate from the network)
/ / three threads are all the same code is to come up with a function it {if (n) (n = = 1 | | n = = 2) {return 1; } return Fib1(n - 1) + Fib1(n - 2); } console.time(' execute time '); Fib1(43) console.timeEnd(' execution time '); self.addEventListener('message', function (e) { console.log(e.data); Self. postMessage(' Pass data: '+ e.data); self.close() }, false);Copy the code



You can see each in the image aboveWorkerAll take about 4 seconds (giFs don’t record very well, they are executed all at once), which means we distribute three of themworkerMaking the original 10 seconds into 4 seconds, a full reduction of more than two. We can use it if we encounter time-consuming operationsworkerTake care of it for us.

Four, use scenarios
  • Encrypt data: When encrypting and decrypting a lot of data, this can be very expensive and cause the UI thread to be unresponsiveworkerThreads allow users to manipulate the UI more seamlessly. For example, upload build files at breakpointshashValue, this is the useworkerGood timing.
  • Big data processing: If the data is too large, sorting, filtering and other operations will be very time-consuming, this is usedworkerDo not use the main thread.
  • .
Five, conclusion

Webworke is a time-wasting operation in most scenarios. You must close it after using it, or it will waste CPU resources and consume performance.

Resources javaScript Advanced Design Program Fourth Edition