Call Stack

The call stack is a mechanism that helps the JS interpreter keep track of the functions called by the script

Each time an execution calls a function, it is added to the top of the call stack, and each time the function exits, the interpreter pops it off the call stack,

Functions can exit either by a return statement or by reaching the end of the scope

Every time a function calls another function, it’s added to the top of the stack, at the top of the calling function,

The call stack handles each function on a first-in, last-out (last-in, first-out) basis, as shown in the previous example:

1. The file loads and calls the main function, which represents the entire file (global context) and is added to the call stack

2. File execution, call calculation, and add it to the top of stack

3. Calculation calls addThree and addThree is added to the top of the stack

AddThree calls addTwo and addTwo is added to the top of the stack

AddTwo calls addOne and addOne is added to the top of the stack

6. AddOne does not call any function and pops it off the call stack when it finishes executing (either by executing a return statement or reaching the end of scope)

7. AddTwo obtains the addOne execution result and pops it out of the call stack

8. AddThree gets the execution result of addTwo and pops it out of the call stack after execution

9. Calculation calls addTwo, adding addTwo to the call stack

AddTwo calls addOne to add addOne to the call stack

11. AddOne does not call any function, and when it is finished, pops it off the call stack

12. AddTwo gets the execution result of addOne and pops it out of the call stack

13. Calculation obtains the results of addThree and addTwo, returns and, and pops up the call stack after execution

14. No statements or function calls are executed in the file, and the main function exits the call stack

You can see the call stack for the current code execution using Chrome’s developer tool source TAB

(Maximum call stack size exceeded)

If you see this error, it means that the function is calling too many functions. The maximum call stack is around 50,000-100,000 calls. If you go beyond this range, your code may be in an infinite loop

The function call that caused this error can be viewed from the output call stack

Browsers prevent code from freezing pages by limiting the size of the call stack

Summary: The call stack is used to track function calls in the code. It follows the principle of first in, last out. Js is single threaded, which means it has only one call stack

Event loops in the browser

Single-threaded JS

Javascript language is a feature of the single thread, that is to say, at the same time can only do one thing, why is a single thread, is associated with its use, is the main purpose of js to interact with the user, and operating the dom, which determine that it is only a single thread, otherwise it will lead to very complex synchronization problems, if the js have two threads at the same time, One thread adds content to a DOM node, and one thread removes it. Which one?

In order to make better use of the computing power of multi-core CPU, HTML5 proposes the ability to enable sub-threads for Web workers, which allows JS scripts to create multiple threads. However, sub-threads are completely controlled by the main thread and cannot operate DOM. Therefore, this standard does not change the nature of JS single threads

What is asynchrony

Single threading means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task has to wait forever. If the queue is computational-heavy, fine, but most of the time the CPU is idle because I/O operations (such as Ajax operations reading data from the network) have to wait for results before they can proceed

In this case, the single-thread approach leads to low execution rate, low CPU utilization,

So there is the so-called asynchronous, a JS script can be divided into synchronous code and asynchronous code, as follows

var a = '123'; function hello() { console.log('hello'); } setTimeout () = > {/ / asynchronous code. The console log (' -- -- -- -- - setTimeout '); }, 1000); hello(); console.log('a'); // hello // a // setTimeoutCopy the code

Asynchrony can be understood as the code being suspended until it is ready to be executed

This code executes as follows:

1. Declare variable A

2. Declare the function hello

3. Call setTimeOut and pass in the callback. At this point, the callback code is suspended until the appropriate time to execute.

4. Call function hello and execute function hello

5. Output variable A

6. The timer triggers setTimeout

Asynchronous tasks include timers, Ajax requests, user events, and so on

It is important to note that asynchronous code is executed only after synchronous code has been executed

That is, synchronous code must be executed before asynchronous code:

    setTimeout(() => {
        console.log('hello');
    }, 0);
    for (let index = 0; index < 100000000; index++) {
    
    
    }
    console.log('a');

    // a 
    // hello
Copy the code

So: the following two are written the same way:

    var req = new XMLHttpRequest();
    req.open('GET', url);    
    req.onload = function (){};    
    req.onerror = function (){};    
    req.send();




   var req = new XMLHttpRequest();
    req.open('GET', url);
    req.send();
    req.onload = function (){};    
    req.onerror = function (){}; 
Copy the code

It is important to note that the timer is not accurate if the synchronous code takes too long to execute, as in the previous example we printed the time

    setTimeout(() => {
        console.log('hello');
    }, 0);
    console.time(1)
    for (let index = 0; index < 100000000; index++) {
    
    
    }
    console.timeEnd(1)
    console.log('a');

    // 82.30517578125 ms
    // a
    // hello
Copy the code

You can see that by executing the for loop you have executed 82+ms

To interject here, in fact the so-called asynchronous, but the browser and open a special threads execute asynchronous operations, such as performing an HTTP request, the browser will have a special thread to perform HTTP requests, when after completion of the HTTP request to inform js the main thread, but for js developers js is indeed a single thread, there is no problem

Event loop

Asynchrony is code that is suspended by the browser, and this code is usually a callback function, which is suspended by the browser until the appropriate time to execute, and what is the appropriate time, which comes to the event loop,

The event loop can be understood as the sequential mechanism by which the browser executes JS code,

Heap, call stack = heap memory and call stack

Web apis are asynchronous apis for browsers such as Ajax setTimeout user events

A callback queue is a first-in-first-out structure in which pending code (callbacks) is placed at the appropriate time for asynchronous operations (timers running out, Ajax returning data, user triggering click)

Event loop: When the synchronous code in the JS script is executed, the event loop will read the callback of the asynchronous operation from the callback queue and put it into the call stack for execution

Let’s look at the first example again

    var a = '123';
    
    function hello() {
        console.log('hello');
    }
    setTimeout(() => {
        console.log('-----setTimeout');
    }, 0);
    hello();
    console.log('a');
Copy the code

.

3. Call the Web API, pass in the callback and 0 parameters, trigger the timer, and put the callback into the callback queue

.

6. After the synchronization code is executed, the Event Loop retrieves the timer callback from the callback queue and puts the execution on the call stack

It is important to note that when the timer is enabled, the timer is already started, rather than waiting for the synchronization code to complete.

It should also be noted that the Event loop reads only one call at a time from the callback queue to the call stack, and does not read from the callback queue again until the call stack is empty again (empty without context)

Promise

The promise introduced in ES5 is slightly different from the callback queue in that it has its own queue and has a higher priority than the callback queue, that is: The Event loop reads the Promise queue first, reads the promise callback if it has one, and places it on the call stack, and reads the callback queue if it doesn’t

The following is an example:

    console.log('a');
    setTimeout(() => console.log('b'));
    new Promise((resolve, reject) => {
      resolve();
    })
    .then(() => {
      console.log('c');
    });
    console.log('d');

    // a
    // d
    // c
    // b
Copy the code

Since promise takes precedence over setTimeout, it will execute first

Promise’s syntactic sugar :async await is the same

console.log('a'); setTimeout(() => console.log('setTimeout')); async function hello() { await new Promise((resolve) => { resolve(123); }); The console. The log (' after await); } hello(); console.log('d'); // a // d // await after // bCopy the code

Also note that the code in the Promise constructor is synchronous code (of course reslove is usually executed in asynchronous code), i.e. :

    console.log('a');
    setTimeout(() => console.log('b'), 0);
    new Promise((resolve, reject) => {
+       console.log('promise constructor');
        resolve();
    })
        .then(() => {
            console.log('c');
        });
    console.log('d');

    // a
    // promise constructor
    // d
    // c
    // b
Copy the code

This is also true with async await

    setTimeout(() => {
        console.log('setTimeout');
    });
    
    
    async function hello() {
        console.log('async ');
        await new Promise((resolve) => {
            console.log('promise');
            setTimeout(() => {
                resolve(123);
            });
        });
        console.log('------');
    }
    hello();
    console.log('a');
    
    // async 
    // promise
    // a
    // setTimeout
    // ------	
Copy the code

Reference links:

www.ruanyifeng.com/blog/2014/1…

Felixgerschau.com/javascript-…