When you first learn to use the for loop, you will encounter the following situation.
Problem of repetition
for (var i = 1; i <= 5; i++) {
setTimeout(function timer() {
console.log(i)
}, i * 1000)}Copy the code
Expected results: 1 2 3 4 5
Print result: 6 6 6 6 6
The solution
closure
for (var i = 1; i <= 5; i++) {
(function (j) {
setTimeout(function timer() {
console.log(j)
}, j * 1000)
})(i)
}
Copy the code
SetTimeout The third parameter
for (var i = 1; i <= 5; i++) {
setTimeout(
function timer(j) {
console.log(j)
},
i * 1000,
i
)
}
Copy the code
Define I using let
for (let i = 1; i <= 5; i++) {
setTimeout(function timer() {
console.log(i)
}, i * 1000)}Copy the code