About the problem encountered in the setTimeout loop in js

the first type of var declares a variable

for(var i=0;i<10;i++){
	setTimeout(()=>{
		console.log(i)
	},0)
}
// Output result: 10 of 10

Since JavaScript is single-threaded and executes sequentially, setTimeout is an asynchronous function that puts the intrinsic into the task queue, and at this point the loop is executed before executing the intrinsic, so when the intrinsic function is executed i is already equal to 10, so it will eventually output 10 10

the second type of let declares the variable

for(let i=0;i<10;i++){
	setTimeout(()=>{
		console.log(i)
	},1000)
}
// Output result: 0-9

Let block-level scope, for outside the loop can not get i, because the for loop header let it rebinded to each iteration of the loop body, ensuring that the value at the end of the previous iteration is reassigned.
The function() in setTimeout belongs to a new scope, the variables defined by var cannot be passed into the function execution domain, by using let to declare that the block variable can act on this block, so the function can use the i variable;

Leave a Reply