This article refers to the "Html 5 and CSS 3 authoritative guide"
After the birth of HTML 5, we can use JavaScript to implement multithreading. H5 added a new Web workers API, using this API, users can easily create a thread running in the background, H5 is called Workder, if it will take longer than the parent's operations in the background to execute, the user in the interface operation is completely unaffected.
Creating a background thread is also very simple, as long as the URL of the script file that needs to be executed is used as a parameter in the Workder class's constructor, and then the Worker object is created, as shown below
var worker = new Worker ("Test.js")
After the worker object has been created, we can send a message to the background thread through the worker's PostMessage (). You can use OnMessage (msg) to get messages.
Let's take a look at the communication between multiple threads, where the communication between several workers is actually required by the main thread, child thread A sends the message to the main thread, and the main thread sends a message to B. The following is the implementation code.
<! DOCTYPE html>
Send.js
OnMessage = function (msg) {PostMessage ("This is a message sent by child thread A");//thread A sends a message}
Receive.js
OnMessage = function (msg) {//alert (msg.data);//This sentence will be an error because the current method is executed in a child thread, so you cannot use alert because this affects UIconsole.log (msg.data) ; Accept thread output in console}
Finally, let's talk about the variables, functions, and classes available in Workder
Self: This keyword is used for the scope of this thread.
PostMessage (MSG) sends a message to the source window where the thread was created.
OnMessage gets the event handle that accepts the message.
Importscripts to import other JavaScript scripts.
Use the Navigator object.
Using Sessionstorage/localstorage
Using AJAX requests
Nested threads
Close ends this thread.
Settimeout/setinterval
Eval (). IsNaN (), etc., all JavaScript core functions can be used.
Object
You can use the WebSockets API.
If there are errors in the content of the article, please criticize it.
Multi-threaded communication in JavaScript