JS function execution timing

The different execution timing of JS functions will affect the output results of the function operation. You cannot judge what the function outputs by the code itself, but according to the specific execution timing of the function.

1 See the code below

let i = 0
for(i = 0; i<6; i++){
  setTimeout(()=>{
    console.log(i)
  },0)
}

Insert picture description here

The above code execution output 6 6s, why? Because setTimeout is an asynchronous task, the operation performed here will be thrown into another task queue by the browser. The browser will continue to execute at this time, and the following code will be executed before the setTimeout function is executed. Operation, this time because the for loop has added i to 6, so all the output is 6.

2 How to make the above code print 0, 1, 2, 3, 4, 5?

for(let i = 0; i<6; i++){
  setTimeout(()=>{
    console.log(i)
  },0)
}

Insert picture description here
Define i into the body of the for loop, and the output is the result we want. Why?

Because the scope of the let variable can only be in the current function, each time the for loop generates a new i, the i output in setTimeout is the new i, and this i will not change, so the output is normal.

3 In addition to using for let, there are other ways to print 0, 1, 2, 3, 4, 5

3.1 Using function closures, we define an anonymous function, and pass the current i as a value into the output, you can print the correct result
let i
for(i = 0; i<6; i++){
	!function(value) {
		  setTimeout(()=>{
		    console.log(value)
		  },0)
	}(i)
}

Insert picture description here

3.2 Use the third parameter of setTimeout, pass i into it and print it as value
let i
for(i = 0; i<6; i++){

		  setTimeout((value)=>{
		    console.log(value)
		  },0,i)

}

Insert picture description here

3.3 Using the const keyword
let i
for(i = 0; i<6; i++){
	const x = i
	setTimeout(()=>{
	   console.log(x)
	 })
}

Insert picture description here

Published 38 original articles · praised 17 · views 9007

Guess you like

Origin blog.csdn.net/cainiao1412/article/details/101527941