SoFunction
Updated on 2025-02-28

JavaScript running mechanism example analysis

This article describes the JavaScript operation mechanism. Share it for your reference, as follows:

First time blogging

Currently, in the second semester of the first and second semesters of the study, I started to get started with the front end of my sophomore year. However, I have been a simple call to the framework for a long time and have not conducted in-depth research on it. Therefore, this blog is the beginning of self-supervision. The content of this blog originated from writing a WeChat mini program front-end some time ago. I found that the rendering order of the page always goes against my expectations. Therefore, I recently read some blogs and documents about the JavaScript operating mechanism and have some basic frameworks. Let’s take a closer look at what I have learned.

JavaScript execution order

First of all, JavaScript is executed in order, line by line, and JS has only one thread, that is, it is impossible to execute two codes at the same time. That is to say, when one code is executed, all the code behind it needs to wait until the code is executed, and the subsequent execution can continue to be executed. If this is the case, it will lead to extremely poor user experience. For example, if a request is sent to the server, the subsequent code will wait until the server returns the result, and the user can only perform new operations.

What's going on?

Explain the JavaScript execution mechanism in detail

JavaScript execution stack

JavaScript executes code in a stack-pressed manner. The stack is empty when it is executed at the beginning. When the execution begins, the JS engine will put the code on the bottom of the stack. If the code contains calls from other functions, the called function is placed on the top of the stack. If the code does not contain calls from other functions, the function will be executed, and after the execution is completed, the stack will be released, and so on, and finally until the stack is empty.

Synchronous and asynchronous tasks in JavaScript

In fact, the real JS internals are synchronous and asynchronous tasks, but this does not change the characteristics of JS single thread.

  • Synchronous task: directly return the result after execution, example: (); c = a + b
  • Asynchronous task: The result cannot be returned immediately after execution. You need to wait for a certain period of time before you can execute the callback function and operate on the return result.

In the system, JS has a main thread, which will first execute all synchronous tasks, and the asynchronous tasks will be registered first. Then the main thread will not wait for the return of the asynchronous task execution result, but will continue to execute the following synchronous tasks (in this process, if the asynchronous task returns the result, the next callback function will be placed in the Event Queue to wait), until all synchronous tasks are executed, the main thread will read the task from the Event Queue to execute. This process will continue to loop, that is, the Event Loop event loop.

How does event loop happen

Don’t you find it strange? If you follow the above-mentioned synchronous tasks and asynchronous tasks, then can’t it be executed in one round? Where did the Event Loop come from?

This is a small detail. When there are multiple asynchronous tasks, the time required for the result returned by each asynchronous task is different. This means that Event Queue queues the return result in a first-in-first-out form. When the first asynchronous task returns the result, it is placed at the first place in the queue, and the next asynchronous task follows closely, and it is lined up in a queue. When the main thread is idle (that is, after the synchronization task is executed), the event is read from the Event Queue and put it into the main thread for execution. The loop comes from that when the Event Queue is executed, after a period of time, the previous asynchronous task returns the result. Put it in the Event Queue. The monitor detects that the Event Queue is non-empty, and the main thread starts to execute the tasks in the Event Queue again.

Macro and micro-tasks

Before explaining the definition, we first explain the asynchronous task:

  1. Asynchronous requests to servers: The most common asynchronous task, which involves the interaction between front and back ends, requires the server to process the request and return the request result.
  2. setTimeout and setInterval: Delay operation, the latter is a loop operation (both involves delay values)
  3. Promise: Object used by JS to handle asynchronous operations
  4. (callback): Similar version of "setTimeout", calling the callback callback function in the next loop of the event loop.

Broadly speaking, JS is divided into synchronous tasks and asynchronous tasks, and here is a more detailed definition of tasks:

  • macro-task: including overall code script, setTimeout, setInterval
  • micro-task: Promise,

Here, the reason why macro tasks and micro tasks are proposed is to better understand the event loop!

Execution process:

  • The main thread will execute the macro tasks of the first loop in order, and then put the micro tasks encountered in the first loop into the Event Queue of the micro task, and put the macro tasks encountered into the macro task Event Queue. Pay special attention here! ! The first macro task of looping is the overall script code! ! ;
  • Then execute the Event Queue of the microtask;
  • During the second loop, the first macro task will be taken out from the Event Queue of the macro task, and then the code contained in the current macro task will be executed. The micro task you encountered will be placed into the Event Queue of the micro task, and the macro task you encountered will be placed into the Event Queue of the macro task;
  • Then execute the tasks in the Event Queue of the current micro-task;
  • The third loop is to take out the second macro task from the Event Queue of the macro task... (using this loop)

In short, it is to execute macro tasks first and then micro tasks.Pay special attention to two pointsJust:

  1. The macro task of the first loop is the overall script code
  2. The macro task queue is a cycle to execute a macro task

Here is an example:

 ('1');
 
 setTimeout(function() {
  ('2');
  (function() {
   ('3');
  })
  new Promise(function(resolve) {
   ('4');
   resolve();
  }).then(function() {
   ('5')
  })
 })
 (function() {
  ('6');
 })
 new Promise(function(resolve) {
  ('7');
  resolve();
 }).then(function() {
  ('8')
 })
 
 setTimeout(function() {
  ('9');
  (function() {
   ('10');
  })
  new Promise(function(resolve) {
   ('11');
   resolve();
  }).then(function() {
   ('12')
  })
 })
 
 //Author: ssssyoki //Link: /post/59e85eebf265da430d571f89 //Source: Nuggets

The output order is:

1,7,6,8,2,4,3,5,9,11,10,12

Summarize

This blog may contain some nouns or methods that you have never heard of, and I have not explained them in detail. The reason for this is that, personally, when I read some materials, I often encounter things I don’t understand. I will choose to read and understand myself, so that it is more effective in memorizing and thorough understanding, just like looking up words. If I tell you directly in the text, I will not pay attention to it.

Interested friends can use itOnline HTML/CSS/JavaScript code running toolhttp://tools./code/HtmlJsRunTest the above code running effect.

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript DOM skills》、《Summary of JavaScript page element operation skills》、《A complete collection of operations and techniques related to JavaScript events》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.