Home Web Front-end JS Tutorial What is the order in which JS code is executed?

What is the order in which JS code is executed?

Dec 31, 2017 am 11:35 AM
javascript order

What I bring to you this time is the order in which JS code is executed. Strictly speaking, javascriptThere is no concept of multiple threads. All programs are single Threads are executed sequentially. This article will give you a detailed analysis.

1. What is single thread?

In layman’s terms, when the code is executing, if another piece of code wants to be executed, it must wait until the current code is executed. Let's take a piece of code to explain it

for(var i=1;i<=3;i++){
  setTimeout(function(){
    console.log(i); //输出:4,4,4
  },0)
}
Copy after login

Let's take a look at the above code. Since the delay time is set to 0, then the loop should be executed once and an i should be printed immediately, but in the end The printed result is: 4, 4, 4. The reason why the above results occur is precisely because the js code is a single-threaded application.

During the execution process, for loop is encountered first, and the for loop enters the thread first. When i=1, after the loop reaches setTimeOut, the for loop has not yet completed execution, and setTimeOut will be put into a place (thread pool) to wait for execution. At this time, the for loop continues to execute. When i=2, the for loop has not yet finished executing. At this time, setTimeOut will still be placed in the thread pool waiting for execution... and so on, until the for loop completes 3 times, the for loop After the execution is completed, the thread is idle at this time. The setTimeOut waiting for execution in the thread pool executes and prints i in sequence. After the for loop execution is completed, i becomes 4, so three 4s are printed.


2. If you want to change the above situation, you can use the following code

//将var变为let
for(let i=1; i<=3; i++){
  setTimeOut(function(){
    console.log(i); //输出的结果为1,2,3
  },0);
}
//用自执行函数进行包裹
for(var i=1; i<=3; i++){
  !function(i){
    setTimeOut(function(){
      console.log(i); //输出的结果为1,2,3
    },0);
  }(i)
}
Copy after login


2. # in js ##Function scope and code execution

 >>>Function scope

Let’s first understand the following concepts:

 1 , In the js language, there is no block-level scope similar to

c language.

 2. The top-level scope in the js language is within the

window object scope, which is called the global scope. Variables declared in the global scope are global variables.

 3. Variables within the scope of a js function can only be used inside the function and cannot be used outside the function. Such variables are local variables.

 4. JS functions can be nested. The nesting of multiple functions constitutes the layer-by-layer nesting of scopes. This is called the scope chain in JS.

5. JS scope chain variable access rules:

(1) When the variable to be accessed exists in the current scope, use the variable in the current scope.

   (2) When the variable to be accessed does not exist in the current scope, it will be searched in the upper scope until the global scope.

 >>>Execution sequence

js code execution is divided into two parts:

1. Code checking and loading stage (pre-compilation stage), this stage Declare variables and functions, but do not assign values ​​to variables. The default value of variables is undefined.

 2. The execution phase of the code. In this phase, variables are assigned values ​​and functions are declared.

After looking at some of the specific concepts above, let’s take a piece of code to illustrate:

var a=1; //声明了一个全局变量
function func(){
  console.log(a); //输出:undefined。打印a,而在func这个作用域中已经声明了a变量,按照js的执行顺序,此时的a并未被赋值。
  var a=1;
  console.log(a); //输出:1。
}
func();
Copy after login
Look at the above code: the first a outputs undefined. Reason: According to the access rules of js scope chain, the variable a to be accessed exists in the current scope, so the variable in the current scope is used. According to the execution order of the js code, a at this time is only declared but not assigned. The default is undefined, so undefined is output.

The second a outputs 1. It is precisely because a has been declared and assigned a value at this time, so a outputs 1.



I believe you have mastered the method after reading the above introduction. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

Detailed introduction to the use of require.js

Using jQuery to deduplicate arrays Sorting operations

How to use the ES6 destructuring assignment function

The above is the detailed content of What is the order in which JS code is executed?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles