search
HomeWeb Front-endJS TutorialDetailed explanation of the order of code execution in JavaScript

1. js--->Single thread

Strictly speaking, javascriptdoes not have the concept of multiple threads, all programs are executed sequentially by a single thread.

  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)
 }

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)
}

2. Function scope# in js ##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();

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.


Summarize

The above is the detailed content of Detailed explanation of the order of code execution in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor