i have a small for loop, but it is skipping even count , what am I missing ?
var i = 0;
function myLoop() {
setTimeout(function() {
//code below
console.log(Date() ' and count is ' i );
//code above
if (i < 20) {
myLoop();
}
}, i )
}
myLoop()
CodePudding user response:
Your i in the console.log statement is modifying your i variable.
i is equal to i = i 1.
Replace i with (i 1), which will evaluate correctly without modifying i in the process.
This works:
var i = 0;
function myLoop() {
setTimeout(function() {
//code below
console.log(Date() ' and count is ' (i 1));
//code above
if (i < 20) {
myLoop();
}
}, i )
}
myLoop()
CodePudding user response:
i is equal i = i 1; But when you call console.log(i ), first thing wil be console.log with Old value, and after increment your value.
