jquery multiple methods are executed first, java multiple methods are executed in order

This article mainly introduces the execution sequence of multiple jquery methods, which has certain reference value. Friends in need can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to understand it together.

Reference documentation: Timer

1. Why is js single-threaded?

Java is a single-threaded language. Single-threading means that the code executed must be in order and can only do one thing at the same time.
As a browser scripting language, the main purpose of JS is to interact with users and operate the installation steps of the DOMPython interpreter. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. In order to take advantage of the computing power of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JS scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not operate the DOM. Therefore, this new standard does not change the single-threaded nature of JS.

2. Browser thread

Browsers are multi-threaded, and they cooperate with each other under kernel control to maintain synchronization. A browser implements at least three resident threads: JavaScript engine thread, GUI rendering thread, and browser event triggering thread. The JS engine is single-threaded, but the browser can be multi-threaded. Timer timing, network requests, browser rendering, etc. are all completed by different threads.
(1) The java engine is based on event-driven single-thread execution (the DOM can be modified, which simplifies processing) and must comply with the ECMAScript specification. The JS engine has been waiting for the arrival of tasks in the event loop and then processes them (only when the current function execution stack is completed will it fetch tasks from the task queue for execution). The browser has only one JS thread running the JS program at any time.
(2) The UI rendering thread is responsible for rendering the browser interface. This thread will be executed when the interface needs to be repainted (Repaint) or when a reflow is caused by a certain operation. However, the GUI rendering thread and the JS engine are mutually exclusive. When the JS engine is executed, the GUI thread will be suspended. JS operations on the page, that is, updates to the GUI, will also be saved in a queue, and will not be available until the JS engine is idle. be executed. This is JS blocking page loading
(3) Event triggering thread. When an event is triggered, the thread will add the event to the end of the task queue and wait for processing by the JS engine. These events can come from the code block currently executed by the JavaScript engine calling setTimeout/ajax to add a task, or from other threads in the browser such as tasks added by mouse clicks. However, due to the single-threaded relationship of JS, all these events have to be queued and waited for processing by the JS engine.

Note:
The browser renders the page 60 times in 1 second, and a UI render task is added to the Render queue every 16ms. But the browser only has a chance to perform this task when the stack is empty. Splitting the task through setTimeout(cb,0) increases the chance of the UI render task being executed and improves the user experience.

You can look at the picture below to deepen your understanding:
chrome threads

3.Event loop
Dom tree is not thread-safe. Because of this limitation, js code should be executed in a single thread. However, at the same time, it must be ensured that the js engine handles all events and does not miss any function calls. So we talk about Event loop.

The event loop can be briefly described with the following picture:
Event loop

  • Call stack is a call stack that contains all functions that are about to be called.
  • Event handlers queue, is a queue of event handlers to be executed, arranged using different algorithms according to priority
  • Event loop, checks if the event handler queue is empty, if not then calls top and removes it.
  • JavaScript Web APIs, these are APIs provided by the browser, such as AJAX requests, etc., which are actually browser threads, not JS.
    The whole process is similar to the following code:
    When the call stack is empty, the browser checks whether it should render the current page, and then checks the Event handler queue.
while(true){
    if(renderEngine.isItTimeToRender(){
        renderEngine.render();
    }
 
    if(eventHandlersQueue.isNotEmpty()){
        eventHandlersQueue.processTopEventHandler();
    }
}
4. How to implement concurrency in JS?

There are two methods, one is based on the setTimeout() method, and the other is using WebWorkers.

setTimeout(): used to call a function or calculated expression after a specified number of milliseconds
In fact, the browser’s timer thread is used to put the task into the event queue within the specified time and wait for the js engine to be idle for execution.
Its approach is to break execution into simple tasks so that the browser rendering thread can have a chance to execute.
eg:
Here is a way to infinitely approximate the PI value:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="results">results</div>
    <>
    var results = document.getElementById("results");
    function appendResult(result) {
        var div = document.createElement('div');
        div.innerText = result;
        results.appendChild(div);
    }

    // function calculatePi(numberOfIterations) {
    // var pi = 0,
    // n = 1;
    // for (var i = 1; i < numberOfIterations; i + + ) {
    // console.log("I was called");
    // appendResult(pi);
    // pi = pi + (4 / n) - (4 / (n + 2));
    // n + = 4
    // }
    
    // return pi;
    // };
 
    function calculatePi(pi, n) {;
        for (; ; n + = 4) {
            pi = pi + (4 / n) - (4 / (n + 2));
            if ((n - 1) % 20000000 == 0) {
                console.log("I was called");
                appendResult(pi);
                setTimeout(function () {
                    calculatePi(pi, n + 4);
                });
                return;
            }
        }
    }
 
calculatePi(0, 1);
</>
</body>
</html>

It can be seen that after the uncommented part is executed, the browser displays a value close to PI in time. The browser timing trigger continuously adds new tasks to the js engine thread queue. After the js engine execution is completed, the browser GUI rendering thread starts rendering. Display the PI value and then repeat.
When using the comment part of the code, because the js engine thread is never empty, the GUI rendering thread cannot execute (they are mutually exclusive), so the page is always blank.

Web Worker
Reference documents:

  • MDN Web Worker
  • IBM Web Worker

Since the W3C formulated the first HTML5 draft in 2008, HTML5 has carried more and more new features and functions. It not only enhances the performance of web systems or web pages, but also adds support for web application functions such as local databases. Among them, the most important one is support for multi-threading. The concept of worker thread (Web Worker) was proposed in HTML5, and the three main characteristics of Web Worker were standardized: the ability to run for a long time (response), ideal startup performance, and ideal memory consumption. Web Worker allows developers to write background programs that can run for a long time without being interrupted by users, to execute transactions or logic, and at the same time ensure that the page responds to users in a timely manner.

In HTML5, the emergence of worker threads makes multi-threaded programming possible in Web pages. As we all know, JavaScript in traditional pages (before HTML5) works in a single-threaded manner. Although there are many ways to simulate multi-threading (for example: setinterval method, setTimeout method, etc. in JavaScript), but In essence, the running of the program is still performed by the JavaScript engine in a single-threaded manner. The worker thread introduced in HTML5 allows the browser-side JavaScript engine to execute JavaScript code concurrently, thereby achieving good support for browser-side multi-threaded programming.

Note: The DOM cannot be operated. The main purpose of the workers thread is heavy background operations.

eg:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input type="button" value="start" id = "startButton">
    <div id="output">test</div>
    <>
var output = document.getElementById("output");
var startButton = document.getElementById("startButton");
// Some magic to run function as WebWorker
var workerBlob = new Blob(["(" + worker.toString() + ")()"], { type: 'text/java' }),
    workerInstance;
 
startButton.onclick = function () {
    if (workerInstance) {
        workerInstance.terminate(); //If there is a worker thread instance, interrupt first
    }
 
    output.innerHTML = "";
    //The parameter is the URL of the script that the worker will execute, it must comply with the same origin policy
    workerInstance = new Worker(URL.createObjectURL(workerBlob));
    //Receive messages from workers
    workerInstance.onmessage = function (e) {
        output.innerHTML + = "<div>" + e.data + '</div>';
    };
    //Send a message to start the worker
    workerInstance.postMessage(null);
};
 
function worker() {
    onmessage = function (e) {
        var pi = 0,
              n = 1;
        for (var n = 1; ; n + = 4) {
            pi = pi + (4 / n) - (4 / (n + 2));
 
            if ((n - 1) % 200000000 == 0) {
                postMessage(pi);
 
            }
        }
    };
}
    </>
</body>
</html>
5. Summary

Answering the question, JavaScript is single-threaded in the same context, but browser Web APIs are not. Also we have possibility of simulating parallelism by using setTimeout function or, with some limitations, by the use of the real parallelism provided by WebWorkers.( You can see that JS is single-threaded in the same context, but the browser’s Web APIS is not. Likewise we can use setTimeout() to simulate parallelism, or we can use restricted WebWorkers to really parallelize)