1 Explain why the following code prints six 6’s
let i = 0
for(i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
First of all, JS is a single-threaded language, and the execution of each piece of code is like an assembly line, flowing down step by step. The operation mechanism of setTimeout delay is that it will first put the callback function into the waiting queue, and execute the callback function in time order after the execution of other main programs in the waiting area. It’s essentially a matter of scope. The scope of I is global, so you end up printing six 6’s in a row.
Create scope for I artificially, save the value of record I.
Write a method to make the above code print 0, 1, 2, 3, 4, 5
for(let i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
According to ES6 syntax, let and for loops are combined and each iteration holds a value of I in the loop field, so the call of the anonymous function closure inside setTimeout() will get the value of the current iteration.
3 Other methods can print 0, 1, 2, 3, 4, and 5
- Scheme one provides an artificial closure environment of I using immediate execution functions
for(var i = 0; i<6; i++){ (function(j) { setTimeout( function timer() { console.log( j ); }, 1000); })(i); }Copy the code
- Place the definition and call of setTimeout in separate sections
function timer(i) { setTimeout( console.log( i ), 1000 ); } for (var i=0; i<6; i++) { timer(i); }Copy the code
- SetTimeout takes the third argument
function timer(i){
console.log(i);
}
for (var i = 0; i < 6; i++) {
setTimeout(timer,1000,i);
}
Copy the code