current position:Home>JavaScript advanced threading mechanism and event mechanism

JavaScript advanced threading mechanism and event mechanism

2022-04-29 08:09:24Chen Chen is trying

Four 、 Thread mechanism and event mechanism

1、 Processes and threads

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-YNi9qdim-1650515381514)(.\JavaScript senior .assets\image-20210728115630974.png)]

Ⅰ- process

  1. An execution of a program , it Occupy a unique memory space
  2. Can pass windows The task manager looks at the process
  • It can be seen that the memory space of each program is independent of each other

Ⅱ- Threads

Concept :

  • It is an independent execution unit in the process
  • It is a complete process of program execution
  • yes CPU The smallest scheduling unit of

Ⅲ- Processes and threads

  1. The application must run on a thread of a process
  2. There is at least one running thread in a process : The main thread --> Automatically created after the process starts
  3. You can run multiple threads in a process at the same time : At this point, we will say that the program is multi-threaded
  4. Data between multiple processes cannot be shared directly --> Memory is independent of each other ( Isolation )
  5. Thread pool (thread pool): A container that holds multiple thread objects , Realize the reuse of Thread objects

Ⅳ- The questions that come out

① What is multiprocessing and multithreading ?

Multi process running : An application can start multiple instances at the same time

Multithreading : In a process , There are multiple threads running at the same time

② Compare single threaded to multithreaded ?

Multithreading :

  • advantage :

  • Can effectively improve CPU Utilization ratio

  • shortcoming

  • Creating multithreading overhead

  • Switching overhead between threads

  • Deadlock and state synchronization

Single thread :

  • advantage : Sequential programming is easy to understand
  • shortcoming : Low efficiency

③ JS Single thread or multi thread ?

JS It's single threaded , But use H5 Medium Web Workers It can be multithreaded

  • Only one thread can operate DOM Interface
  • The specific reasons can be seen below 3、JS It's single threaded The detailed explanation given in part

④ Is the browser running single threaded or multi-threaded ?

It's all multithreaded

⑤ Is the browser running in a single process or multiple processes ?

Some are single process :

  • firefox
  • Old version IE

There are many processes :

  • chrome
  • new edition IE

How to check whether the browser is multi process running ? Task manager –> process

2、 Browser kernel

The core program that supports the browser to run

Ⅰ- Different browser kernels

  • Chrome, Safari : webkit
  • firefox : Gecko
  • IE : Trident
  • 360, Sogou and other domestic browsers : Trident + webkit

Ⅱ- What modules does the kernel consist of ?

The main thread

  1. js Engine modules : be responsible for js Program compilation and operation
  2. html,css Document parsing module : Responsible for parsing page text ( Take apart )
  3. dom/css modular : be responsible for dom/css Related processing in memory
  4. Layout and rendering module : Responsible for the layout and rendering of the page
  5. Layout and rendering module : Responsible for the layout and rendering of the page

Sub thread

  • Timer module : Responsible for the management of timers
  • Web request module : Responsible for server requests ( routine /Ajax)
  • Event response module : Responsible for the management of events

legend

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-L11qPSAB-1650515336636)(.\JavaScript senior .assets\image-20210728141032723.png)]

3、 The thought caused by the timer

<body>
<button id="btn"> Start timer </button>
<script type="text/javascript">
document.getElementById('btn').onclick = function () {
     
var start = Date.now()
console.log(' Before starting the timer ...')
setTimeout(function () {
     
console.log(' The timer executed ', Date.now()-start) // Timers don't guarantee real timing , Usually a little late 
}, 200)
console.log(' After starting the timer ...')
//  Do a long-time job 
for (var i = 0; i < 1000000000; i++) {
      // It will cause the timer to extend for a long time 
...
}
}
</script>
</body>

Ⅰ- Are timers really timed ?

  • Timers don't guarantee real timing
  • Usually a little late ( Acceptable ), It can also be delayed for a long time ( Can't accept )

Ⅱ- Is the timer callback function executed in threads ?

Executed in the main thread , JS It's single threaded

Ⅲ- How the timer is implemented ?

The event loop model , Give a detailed explanation below

3、JS It's single threaded

Ⅰ- How to prove JS Execution is single threaded

  • setTimeout() The callback function of is executed in the main thread
  • The timer callback function can only be executed after all the code in the runtime stack has been executed
//  How to prove JS Execution is single threaded 
setTimeout(function () {
      //4.  Will be [timeout 1111] After the pop-up window is closed , Wait another second   Execute here 
 console.log('timeout 2222')
 alert('22222222')
}, 2000)
setTimeout(function () {
      //3.  After a second   Print  timeout 1111 And pop up , If you don't close the pop-up window here , The above... Will not continue 222
 console.log('timeout 1111')
 alert('1111111')
}, 1000)
setTimeout(function () {
      //2.  And then print timeout() 00000
 console.log('timeout() 00000')
}, 0)
function fn() {
      //1. fn()
 console.log('fn()')
}
fn()
//----------------------
console.log('alert() Before ')
alert('------') // Pause the execution of the current main thread ,  Pause the timing at the same time ,  Click OK ,  Resume program execution and timing 
console.log('alert() after ')

Process results :

  1. First print [fn()], Then it was printed immediately [timeout() 00000]
  2. After a second Print timeout 1111 And pop up , If you don't close the pop-up window here , The above... Will not continue 222
  3. Will be [timeout 1111] After the pop-up window is closed , Wait another second Execute here
  • ask : Why is it clearly written 2 second , But close the last pop-up window and execute in another second ?
  • Explain : It's not calculated after closing , It's calculated together ,alert It just pauses the execution of the main thread

Ⅱ-JS The basic flow and code classification of the engine executing code

Code classification :

  • Initialization code
  • callback code

js The basic flow of engine execution code

  1. First execute the initialization code : Contains some special code Callback function ( Asynchronous execution )
  • Set the timer
  • Binding event listening
  • send out ajax request
  1. The callback code will be executed at a later time

Ⅲ- Why? js To use single threaded mode , Instead of multithreading ?

  1. JavaScript The single thread , Related to its use .
  2. As a browser scripting language ,JavaScript Its main purpose is to interact with users , And operation DOM.
  3. This determines that it can only be a single thread , Otherwise, it will bring complicated synchronization problems
    • Take a chestnut : If we want to update one on the page dom The node is then deleted , Using single thread is no problem
    • But if multithreading , When I delete a thread, I delete it first dom node , When the update thread wants to update, it will make an error

4、 The event loop model (Event Loop) Mechanism

Ⅰ- The concept leads to

We all know ,javascript Since its birth, it is a single thread non blocking scripting language . This is determined by its original use : Interact with browsers .

Single thread means ,javascript Code at any time of execution , There is only one main thread to handle all tasks .v

Non blocking :

Non blocking is when the code needs to do an asynchronous task ( Unable to return results immediately , A task that takes some time to return , Such as I/O event ) When , The main thread will suspend (pending) This task , Then when the asynchronous task returns the result, it will execute the corresponding callback according to certain rules .

Single thread is necessary :

It's also javascript The cornerstone of this language , One of the reasons for this is the initial and most important execution environment —— Browser , We need to do all kinds of dom operation . Just imagine If javascript It's multi-threaded , So when two threads are working on dom Do an operation , For example, an add event to it , And the other deleted this dom, How to deal with this ? therefore , To make sure that it doesn't What happens is similar to the situation in this example ,javascript Choose to use only one main thread to execute code , This ensures the consistency of program execution .

Of course , Now people also realize , Single thread ensures the execution order, but also limits javascript The efficiency of , So developed web workers technology . This technology claims to make javaScript Become a multithreaded language .

However , Use web workers There are many limitations to multithreading technology , for example : All new threads are fully controlled by the main thread , Can't execute... Independently . That means that “ Threads ” In fact, it should belong to the child thread of the main thread . in addition , These sub threads are not executing I/O Authority to operate , Only the main thread can share some tasks such as calculation . So strictly speaking, these threads do not have complete functions , So this technology doesn't change javascript The one-way nature of language .

Predictably, , In the future javascript It will always be a single thread language .

Come back , Mentioned earlier javascript Another characteristic of “ Non blocking ”, that javascript How does the engine achieve this ?

The answer is ——event loop( The event loop ).

notes : although nodejs There are also similar event loops in the traditional browser environment . But there are many differences between them , So separate the two , Separate interpretation .

Ⅱ- In the browser environment JS The engine's event loop mechanism

① Execution stack concept

See the notes above for details of the execution context stack --> Function advanced 2、 Execution context and execution context stack , Continue with an overview here to deepen understanding

When javascript When the code is executed, different variables will be stored in different locations in memory : Pile up (heap) and Stack (stack) To distinguish . among , There are some objects in the pile . There are some basic type variables and object pointers in the stack . But the meaning of the execution stack here is different from that of the above stack .

Execution stack :

When we call a method ,js An execution environment corresponding to this method will be generated (context), Also called Execution context . There is a private scope for this method in this execution environment 、 Direction of upper scope 、 Method parameters , The variables defined in this scope and the this object . And when a series of methods are called in turn , because js It's single threaded , Only one method can be executed at a time , So these methods are queued up in a separate place . This place is called the execution stack .

When a script is executed for the first time ,js The engine will parse the code , And add the synchronization code into the execution stack according to the execution sequence , Then start from the beginning . If a method is currently executing , that js The execution environment of this method will be added to the execution stack , Then enter the execution environment to continue to execute the code . When the code in this execution environment After execution and return the result ,js Will exit the execution environment and destroy it , Go back to the execution environment of the previous method . The process goes on and on , Until all the code in the execution stack is executed .

Here we continue to take out the stack diagram to deepen our understanding : Insert picture description here

We can see from the pictures , A method execution will add the execution environment of this method to the execution stack , Other methods can also be called in this execution environment , Even myself , The result is just to add another execution environment to the execution stack . This process can go on indefinitely , Unless there's a stack overflow , That is, it exceeds the maximum memory that can be used .

The above procedures are all about synchronous code execution . So when an asynchronous code ( If sent ajax Request data ) What will happen after implementation ?

Just said js Another big feature of is non blocking , The key to achieving this is the following mechanism —— Event queue (Task Queue).

② Event queue (Task Queue)

JS The engine does not wait for an asynchronous event to return results , It will suspend the event , Continue to perform other tasks in the execution stack , When an asynchronous event returns a result ,js This event will be added to a different queue than the current execution stack , We call it Event queue .

Being put into the event queue does not immediately execute its callback , It is Wait until all tasks in the current execution stack have been executed , When the main thread is idle , The main thread will look up whether the event queue has tasks . If there is , Then the main thread will take out the events in the first place , And put the callback corresponding to this event into the execution stack , Then execute the synchronization code …, So again and again , This creates an infinite cycle . This is the process called “ The event loop (Event Loop)” Why .

Here's a picture to show the process :

In the picture stack Represents what we call the execution stack ,web apis It represents some asynchronous events , and callback queue That is, the event queue .

The above event cycle process is a macro statement , Actually because asynchronous tasks are not the same , So their execution priorities are different . Different asynchronous tasks are divided into two categories : Micro task (micro task) And macro tasks (macro task), This part is explained in detail below

Ⅲ- Macro task (macro task) And micro tasks (micro task)

Macro tasks and micro tasks also belong to Ⅱ- In the browser environment JS The engine's event loop mechanism Internal knowledge points , But I think it's more important , Raise it to its knowledge point

① Explanation of macro task queue and micro task queue

seeing the name of a thing one thinks of its function , Put the macro task into the macro task queue ( Macro queue for short ) in 、 Put the micro task into the micro task queue ( Micro queue for short ) in

  1. JS The queue used to store callbacks to be executed in contains 2 There's a different specific line up
  • Macro queue : Used to save macro tasks to be executed ( Callback ), such as : Timer Callback /ajax Callback /dom Event callback
  • Micro queue : It is used to save the micro task to be executed ( Callback ), such as :Promise The callback /muntation Callback
  1. JS It's different when it's executed 2 A queue :
  • JS The execution engine must first execute all Initialize synchronization task Code
  • Take out the first one every time Before macro task execution , All of them Micro task Take it out one by one and execute

We talked about that earlier , In a cycle of events , The asynchronous event will be put into a task queue after the result is returned . However , According to the type of asynchronous event , This event will actually be sent to the corresponding macro task queue or micro task queue . And when the current execution stack is empty , The main thread will Check whether there are events in the micro task queue . If it doesn't exist , Then go to the macro task queue to get an event and add the corresponding back to the current execution stack ; If there is , Then the callback corresponding to the event in the queue will be executed successively , Until the micro task queue is empty , Then go to the macro task queue to get the first event , Add the corresponding callback to the current execution stack … So again and again , Into the loop .

We just need to remember :** When the current execution stack finishes executing, it will immediately process all the events in the micro task queue , Then go to the macro task queue to get an event . In the same event cycle , Micro tasks always execute before macro tasks **

② Schematic diagram

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-I5DCeJn8-1650515336638)(.\JavaScript senior .assets\Promise System learning _ Schematic diagram of macro task and micro task .png)]

③ Reverse understanding of macro tasks and micro tasks from code

Code example

setTimeout(() => {
      
console.log('timeout callback1()')// Put it into the macro queue immediately 
Promise.resolve(3).then(
  value => {
      
    console.log('Promise onResolved3()', value)// When this macro task is executed   Put it into the micro queue immediately , So after this micro task is executed, the next macro task can be executed  
  }
)
}, 0)

setTimeout(() => {
      
console.log('timeout callback2()') // Put it into the macro queue immediately ,
}, 0)

Promise.resolve(1).then(
value => {
      
  console.log('Promise onResolved1()', value)// Immediately put into the micro queue 
  setTimeout(() => {
     
    console.log('timeout callback3()', value) // Put in macro tasks now 
  }, 0)
}
)

Promise.resolve(2).then(
value => {
      
  console.log('Promise onResolved2()', value)// Immediately put into the micro queue 
}
)
console.log(' Synchronization code ') // The synchronization code executes immediately 

result

' Synchronization code ',
'Promise onResolved1()',
'Promise onResolved2()',
'timeout callback1()',
'Promise onResolved3()',
'timeout callback2()',
'timeout callback3()'

Ⅳ-node The event cycle mechanism in the environment

Don't learn node I'll skip this part and go to the next section Web Workers Take notes

How is it different from the browser environment ?

stay node in , The state of the event loop is roughly the same as in the browser . The difference is node There's a model of its own .node The implementation of the event cycle in is dependent on libuv engine . We know node choice chrome v8 Engine as js Interpreter ,v8 The engine will be js After code analysis, call the corresponding node api, And these api Finally, the libuv Engine driven , Perform the corresponding task , And put different events in different queues waiting for the main thread to execute . So in fact node The event loop in exists in libuv In the engine .

The event loop model

Here's a libuv The model of the event loop in the engine :

//libuv The model of the event loop in the engine 
┌───────────────────────┐
┌─>│        timers         │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
│  │     I/O callbacks     │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
│  │     idle, prepare     │
│  └──────────┬────────────┘      ┌───────────────┐
│  ┌──────────┴────────────┐      │   incoming:   │
│  │         poll          │<──connections───     │
│  └──────────┬────────────┘      │   data, etc.  │
│  ┌──────────┴────────────┐      └───────────────┘
│  │        check          │
│  └──────────┬────────────┘
│  ┌──────────┴────────────┐
└──┤    close callbacks    │
└───────────────────────┘

notes : Each block in the model represents a phase of the event loop

This model is node In an article on the official website , My following explanations are all from this article . I will post the address at the end of the article , Interested friends can have a look at the original .

Detailed explanation of each stage of the event cycle

From the model above , We can make a general analysis of node The order of the event loops in :

External input data –> Polling phase (poll)–> The check phase (check)–> Close the event callback phase (close callback)–> Timer detection phase (timer)–>I/O Event callback phase (I/O callbacks)–> Idle phase (idle, prepare)–> Polling phase …

The general functions of these stages are as follows :

  • timers( Timer detection phase ): In this stage, the callback in timer queue is executed, such as setTimeout() and setInterval().
  • I/O callbacks(I/O Event callback phase ): This stage performs almost all callbacks . But not including close event , Timers and setImmediate() The callback .
  • idle, prepare: This stage is only used internally , You can ignore .
  • poll( Polling phase ): Wait for the new I/O event ,node In some special cases, it will block here .
  • check( The check phase ): setImmediate() The callback of will be executed at this stage .
  • close callbacks( Close the event callback phase ): for example socket.on('close', ...) such close Event callback .

Let's follow the code for the first time to enter libuv The sequence behind the engine explains these stages in detail :

poll( Polling phase )

Be a v8 The engine will be js The code is parsed and passed in libuv Behind the engine , The cycle first enters poll Stage .poll The execution logic of the phase is as follows : To look at first poll queue Is there an event in , If there is a task, the callback will be executed in the first in first out order . When queue It's empty time , Will check if there is setImmediate() Of callback, If there is, enter check Stage the implementation of these callback. But at the same time, it will also check if there is any expiration timer, If there is , Just put these due timer Of callback Put it in the order of call timer queue in , After that, the cycle will enter timer Stage execution queue Medium callback. The order of the two is not fixed , The impact of the environment in which the code runs . If both queue Are empty , that loop Will be in poll Stage stop , Until there is one i/o Event return , The cycle will go into i/o callback Stage and execute the event immediately callback.

It is worth noting that ,poll The stage is in execution poll queue The callback in does not actually execute indefinitely . There are two situations poll Phase will terminate execution poll queue Next callback in :1. All callbacks completed .2. The number of executions exceeds node The limitation of .

check( The check phase )

check The stage is dedicated to the execution of setImmediate() Method's callback , When poll Phase goes into idle state , also setImmediate queue There is callback when , The cycle of events enters this stage .

close callbacks( Close the event callback phase )

When one socket Connect or a handle When suddenly closed ( For example, call socket.destroy() Method ),close The event is sent to this stage to execute the callback . Otherwise the event will use process.nextTick() Method send out .

timers( Timer detection phase )

This stage performs all due... In a first in, first out fashion timer Join in timer In the line callback, One timer callback It means a pass setTimeout perhaps setInterval Callback function set by function .

I/O callbacks(I/O Event callback phase )

As mentioned above , This stage mainly implements most of I/O Event callback , Include some callbacks for the operating system . For example, one TCP When a connection makes a mistake , The system needs to execute a callback to get this error report .

process.nextTick,setTimeout And setImmediate The difference with the use of scenarios

stay node There are three common ways to delay task execution :process.nextTick,setTimeout(setInterval Same as ) And setImmediate

There are some very different differences among the three :

process.nextTick()

Although there is no mention of , But actually node There is a special queue in , namely nextTick queue. Callback execution in this queue is not represented as a phase , At that time, these events will take priority when each stage is completed and ready to enter the next stage . Before the event loop is ready for the next stage , Will check nextTick queue Is there a task in , If there is , Then the queue will be emptied first . And execution poll queue The task in is different from , This operation will not stop until the queue is cleared . That means , Wrong use process.nextTick() Method will result in node Into a dead cycle .. Until memory leaks .

This method is more appropriate ? Here's an example :

const server = net.createServer(() => {
     }).listen(8080);
server.on('listening', () => {
     });

In this case, when , When listen Method is called , Unless the port is occupied , Otherwise, it will be bound to the corresponding port immediately . This means that this port can be triggered immediately listening Event and execute its callback . However , Now on('listening) Not yet. callback Set it up , Of course not callback It can be executed . To avoid this ,node Will be in listen Used in events process.nextTick() Method , Make sure the event is triggered after the callback function is bound .

setTimeout() and setImmediate()

In three ways , These two methods are the easiest to mix up . actually , In some cases, the performance of the two methods is very similar . But in fact , The meaning of these two methods is quite different .

setTimeout() Method is to define a callback , And we hope that this callback will be executed the first time after the time interval we specified . Pay attention to this “ First time execution ”, It means , Affected by the operating system and current tasks , The callback will not be executed exactly after the expected time interval . There are some delays and errors in the execution time , It's inevitable .node Will be able to execute timer Callback the first time to perform the task you set .

setImmediate() Method means immediate execution , But in fact, it will only execute the callback at a fixed stage , namely poll After the phase . Interestingly , The meaning of the name and what was mentioned before process.nextTick() Method is the best match .node The developers also know that there is some confusion in the naming of these two methods , They said they would not change the names of the two methods — Because there are a lot of node The program uses these two methods , The benefits of name swapping are not worth mentioning compared with its impact .

setTimeout() With no time interval setImmediate() It 's very similar in performance . Guess what the result of this code is ?

setTimeout(() => {
     
console.log('timeout');
}, 0);

setImmediate(() => {
     
console.log('immediate');
});

actually , The answer is not necessarily . you 're right , Even node The developers can't judge the order of the two exactly . It depends on the running environment of this code . Various complex situations in the running environment will result in the random order of the two methods in the synchronization queue . however , In one case, you can accurately determine the execution order of two method callbacks , That's in one I/O Event callback . The sequence of the following code is always fixed :

const fs = require('fs');

fs.readFile(__filename, () => {
     
setTimeout(() => {
     
console.log('timeout');
}, 0);
setImmediate(() => {
     
console.log('immediate');
});
});

The answer is always :

immediate
timeout

Because in I/O Event callback ,setImmediate Method's callback will always be timer Before callback .

5、Web Workers

To learn more, you can click the link to see more , Here is only a general understanding of learning -->Web Workers

  1. H5 The specification provides js Implementation of sub threading , named : Web Workers
  2. relevant API
  • Worker: Constructors , Load threaded execution js file
  • Worker.prototype.onmessage: Callback function to receive another thread
  • Worker.prototype.postMessage: Send a message to another thread
  1. Insufficient
  • worker Inner code cannot operate DOM( to update UI)
  • Cannot load across domains JS
  • Not every browser supports this new feature

Ⅰ- throw away a brick in order to get a gem , Draw out useful

Or naphoracci (Fibonacci) Sequence as an example , This thing is inefficient , Can be used to simulate

<body>
<input type="text" placeholder=" The number " id="number">
<button id="btn"> Calculation </button>
<script type="text/javascript"> // 1 1 2 3 5 8 f(n) = f(n-1) + f(n-2) function fibonacci(n) {
        return n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2) // Recursively call  } // console.log(fibonacci(7)) var input = document.getElementById('number') document.getElementById('btn').onclick = function () {
        var number = input.value var result = fibonacci(number) alert(result) } </script>

When I run this line of code , The calculation value passed in is 50 about ( Some even lower ), The whole page will be stuck for a long time ( The window will pop up after the calculation , However, during the period without pop-up window, the user cannot operate ), At this time, you will find the disadvantages of single thread

Ⅱ- Try to use

  1. H5 The specification provides js Implementation of sub threading , named : Web Workers
  2. relevant API
  • Worker: Constructors , Load threaded execution js file
  • Worker.prototype.onmessage: Callback function to receive another thread
  • Worker.prototype.postMessage: Send a message to another thread
  1. Insufficient
  • worker Inner code cannot operate DOM( to update UI)
  • Cannot load across domains JS
  • Not every browser supports this new feature

① The main thread

  1. Create a Worker object
  2. binding [ The main thread receives the data returned by the thread ] Method
  3. The main thread sends data to the sub thread , Wait for the data to be received
  4. Received data fed back by sub thread , Process the data ( Like a pop-up window )
<body>
<input type="text" placeholder=" The number " id="number">
<button id="btn"> Calculation </button>
<script type="text/javascript"> var input = document.getElementById('number') document.getElementById('btn').onclick = function () {
        var number = input.value // Create a Worker object  var worker = new Worker('worker.js') //  Bind the listener to receive messages  worker.onmessage = function (event) {
        // This becomes the callback code , It will not be carried out until the initialization is completed  console.log(' The main thread receives the data returned by the thread : '+event.data) alert(event.data) } //  Send a message to the subthread  worker.postMessage(number) console.log(' The main thread sends data to the sub thread : '+number) } // console.log(this) // window </script>
</body>

② Sub thread

Put the calculation into the sub thread

Be careful :alert(result) alert yes window Methods , Can't call in line break , Global objects in subthreading are no longer window, So it's impossible to update the interface in sub threads

//worker.js
function fibonacci(n) {
     
return n<=2 ? 1 : fibonacci(n-1) + fibonacci(n-2)  // Recursively call 
}

console.log(this)
this.onmessage = function (event) {
     
var number = event.data
console.log(' The sub thread receives the data sent by the main thread : '+number)
// Calculation 
var result = fibonacci(number)
postMessage(result)
console.log(' The split thread returns data to the main thread : '+result)
// alert(result) alert yes window Methods ,  Can't call in line break 
//  Global objects in subthreading are no longer window,  So it's impossible to update the interface in sub threads 
}

Ⅲ- Flow schematic diagram

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-UkTS7E2r-1650515336639)(.\JavaScript senior .assets\image-20210729173545339.png)]

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290809209328.html

Random recommended