How would you fix it?
function count() {
let counter;
for (counter = 0; counter < 3; counter++) {
setTimeout(function () {
console.log('counter value is ' + counter);
}, 100);
}
}
count();- The
let counterdeclarations is operating almost asvardeclaration, its scope is the whole function. - Each iteration of the for loop registers a callback that will be evaluated when the for loop exits, this results in the
countervalue being 3. - setTimeout forms a closure for value
counterand sincecounteris defined on a function level rather than on the block level of the for loopsetTimeoutdoesn't get the appropriate closurecountervalue.
- Move the counter declaration to the for loop, since let is block-scoped, each iteration of it will have its own counter and it will provide the closure needed to setTimeout to get desired results.
- OR
- Move setTimeout into it's own function and invoke it immediately in the for loop, This will make closure containing the required values
function count() {
for (let counter = 0; counter < 3; counter++) {
setTimeout(function () {
console.log('counter value is ' + counter);
}, 100);
}
}
count();const timeout = (counter) => {
setTimeout(function () {
console.log('counter value is ' + counter);
}, 100);
}
function count() {
for (let counter = 0; counter < 3; counter++) {
timeout(counter);
}
}
count();