The paper

There are three resident threads in the browser, respectively

JS engine interface renders event responseCopy the code

Because all three threads need to access the DOM tree at the same time, the browser needs to be mutually exclusive for thread-safety reasons: the interface rendering and event response threads are suspended while the JS engine executes code.

SetTimeout, setInterval is not multithreading, it is just a timed event trigger, they put some JS code into the JS engine queue at the appropriate time.

SetTimeout (aFunction, 0), this line of code appears to mean that aFunction will be executed after 0 seconds, but this does not mean that it will be executed immediately. The other real meaning is to immediately put aFunction code in the current JS engine queue. So the aFunction code cannot be executed until the current block is complete.

Multithreaded Web Worker

It can execute computation-intensive JS code in another thread without causing the page to freeze. However, to ensure thread-safety, the code in the Worker cannot access the DOM.

Web workers are JavaScript that runs in the background and does not affect page performance.

Method of use

The code examples

<! DOCTYPE html><html>
<body>

<p>Count:<output id="result"></output></p>
<button onclick="startWorker()">Start the Worker</button> 
<button onclick="stopWorker()">Stop the Worker</button>
<br /><br />

<script>
var w;

function startWorker()
{
    // Check whether support is supported
    if(typeof(Worker)! = ="undefined")
    {
       // Determine if there is an object
      if(typeof(w)=="undefined")
      {
          // Create a new object
          w=new Worker("/example/html5/demo_workers.js");
      }
      
      // Generates and receives messages from the Web worker
      w.onmessage = function (event) {
        document.getElementById("result").innerHTML=event.data;
      };
    }
    else
    {
          document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers..."; }}// Terminate multithreading
function stopWorker()
{ 
w.terminate();
}
</script>

</body>
</html>
Copy the code

The first step is to create the Web Worker file

var i = 0;

function timedCount() {
    i = i + 1;
    Returns a message to the HTML page
    postMessage(i);
    
    setTimeout("timedCount()".500);
}

timedCount();
Copy the code

The second step checks Web Worker support

if(typeof(Worker)! = ="undefined")
    {
           // Code block...
    }
    else
     {
          document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
     }
Copy the code

Step 3 Create the Web Worker object

// Checks if there is a worker, if not, it creates a new Web worker object and then runs the code in "demo_workers.js"
if (typeof(w) == "undefined") {
    w = new Worker("demo_workers.js");
}
Copy the code

Step 4 generates and receives messages from the Web worker

// Add an "onMessage" event listener to the Web worker
// Data from the Web worker is stored in event.data
w.onmessage = function(event){
    document.getElementById("result").innerHTML = event.data;
};
Copy the code

Step 5 Terminate the Web Worker

function stopWorker()
{ 
    w.terminate();
}
Copy the code

Step 6 Reuse Web workers

// If you set the worker variable to undefined, you can reuse this code after it is terminated
function stopWorker()
{ 
    w.terminate();
    w = undefined;
}
Copy the code

conclusion

1. Avoid writing computationally intensive front-end code.

2. Use asynchronous Ajax.

3. Avoid writing JS code that takes a long time to execute, such as generating a large table. In this case, you can do it in batches, such as using setInterval to generate 20 rows per second, or continue to generate new rows as the user drags down the scrollbar.

4. Do not perform too much initialization code during page initialization, otherwise it will slow down the page rendering. Some code that does not need to be executed immediately can be executed after the page is rendered, such as binding events and generating controls such as menus.

5. For complex pages (like taobao home page), you can combine asynchronous Ajax to generate pages in batches. Page content is progressively loaded from top to bottom using asynchronous Ajax and filled into the frame. This allows users to see the page earlier.

6. SetTimeout (function, 0) is useful. It allows the callback to be executed as another event response code. After executing the code that implements the current event, render the DOM and execute the setTimeout callback. This allows some code to be deferred and render the DOM before it does.