js execution sequence analysis
JavaScript is a descriptive scripting language that is dynamically parsed and executed by the browser. There are generally two ways to define functions. Browsers have different parsing orders for different ways. This article mainly shares with you the js execution sequence analysis, hoping to help everyone.
The code is as follows:
//“定义式”函数定义 function Fn1(){ alert("Hello World!"); } //“赋值式”函数定义 var Fn2 = function(){ alert("Hello wild!"); }
During the page loading process, the browser will scan each js code block (or file) on the page or loaded. If it encounters a definition If you encounter an assignment-type function, preprocessing will be performed (similar to compilation of C, etc.). After the processing is completed, execution will start from top to bottom; if you encounter an assignment-type function, you will just assign the function to a variable without preprocessing (similar to 1. (Principle that variables must be defined first and then referenced), they will not be processed until they are called. Here is a simple example:
The code is as follows:
//“定义式”函数定义 Fn1(); function Fn1(){ alert("Hello World!"); }
Execute normally, "Hello World!" pops up, the browser preprocesses Fn1, and then starts execution from Fn1(); .
The code is as follows:
//“赋值式”函数定义 Fn2(); var Fn2 = function(){ alert("Hello wild!"); }
Firebug reports an error: Fn2 is not a function. The browser does not preprocess Fn2 and executes it sequentially, so the error Fn2 is not defined.
3. Processing of code blocks and js files
"Code block" refers to a pair of The js code wrapped in the tag refers to the file, nonsense:D
The browser scans each block or file independently, and then executes the global code sequentially (mentioned in 2). Therefore, in one block (file), the function can be "defined" after the call; but in two blocks, the block in which the function is defined must be before the block in which the function is called.
It’s very convoluted, just look at the example:
The code is as follows:
<script type="text/javascript"> Fn(); </script> <script type="text/javascript"> function Fn(){ alert("Hello World!"); } </script> // 报错:Fn is notdefined,两个块换过来就对了
4. Repeatedly defining a function will overwrite the previous definition
This is the same as the variable The repeated definition is the same, the code:
The code is as follows:
function fn(){ alert(1); } function fn(){ alert(2); } fn(); // 弹出:“2”
What if this is the case:
The code is as follows:
fn(); function fn() { alert(1); } function fn() { alert(2); } // 还是弹出: “2”
Still pops up "2", why? 2 has all been explained...
5. The execution of the body's onload function and the body's internal function
The internal function of the body will be executed before the onload function. Test code:
The code is as follows:
//html head... <script type="text/javascript"> function fnOnLoad(){ alert("I am outside the Wall!"); } </script> <body onload="fnOnLoad();"> <script type="text/javascript"> alert("I am inside the Wall.."); </script> </body> //先弹出“I am inside the Wall..”; //后弹出“I am outside the Wall!”
The triggering condition of the body's onload event is that the body content is loaded, and the js code in the body will run before this event is triggered (why? 6 tells you...)
6. Is JavaScript multi-threaded or single-threaded?
Strictly speaking, JavaScript does not have the concept of multi-threading. All programs are executed "single-threaded" in sequence.
To give an inappropriate example:
function fn1(){ var sum = 0; for(var ind=0; ind<1000; ind++) { sum += ind; } alert("答案是"+sum); } function fn2(){ alert("早知道了,我就是不说"); } fn1(); fn2(); //先弹出:“答案是499500”, //后弹出:“早知道了,我就是不说”
Then you must ask: Aren’t delayed execution and Ajax asynchronous loading multi-threaded? Yes, the following program does look like "multi-threading":
The code is as follows:
function fn1(){ setTimeout(function(){ alert("我先调用") },1000); } function fn2(){ alert("我后调用"); } fn1(); fn2(); // 先弹出:“我后调用”, // 1秒后弹出:“我先调用”
It seems that fn2() and the delay program are separated into two processes, but in fact, This is the "callback" mechanism in JavaScript at work, which is similar to the "interrupt and response" in the operating system - the delay program sets an "interrupt", then executes fn2(), and then calls back after 1000 milliseconds are up. Execute fn1().
Similarly, the function called by the body's onload event in 5 also uses the callback mechanism-after the body is loaded, the callback executes the fnOnLoad() function.
The same is true for the data processing functions in Ajax requests.
For a more in-depth discussion of JavaScript thread issues, see this article My opinion on threads in JavaScript and the introduction to JavaScript multi-threaded programming on infoQ.
I’m sleepy, let’s talk about the callback function.
7. Callback function
What is the callback function used for? It’s just a function executed by callback, nonsense :D
As mentioned in 6, the most common callbacks are the calling functions of browser events such as onclick, onmouseotutorialver, onmousedown, onload, etc.; and the processing of Ajax asynchronous request data. Function; setTimeOut delayed execution, setInterval loop execution function, etc.
Let’s just write a pure callback function to play:
The code is as follows:
function onBack(num){ alert("姗姗我来迟了"); // 执行num个耳光 } function dating(hours, callBack){ var SP= 0; // SP,愤怒值 //女猪脚在雪里站了hours个钟头 //循环开始.. SP ++; //循环结束... callBack(SP); } dating(1, onBack);
Related recommendations:
About js execution order solution ideas
JS execution order in the page_javascript skills
JavaScript execution order analysis
The above is the detailed content of js execution sequence analysis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,
