Please find my snippet here,
for (var i=0;i<11;i++) {
setTimeout( () => console.log(i), 10);
}
How it print 11
for 11 times? since i
was set < 11?
if i console it without function it print 1-10 .
for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}
this gives me 1-10. i am wonder how its getting changed if i include function without condition?
Answer
Root case for:
for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}
that console.log
will be triggered directly (without any delay), so it should be:
for (var i=0;i<11;i++) {
setTimeout(function () { console.log(i); }, 10);
}
that will give directly the same result as for ES6
Right way will be by using closures:
for (var i=0;i<11;i++) {
((i) => {
setTimeout(() => console.log(i), 10);
})(i);
}
The reason for that that we have a single-threaded model in JavaScript. So, all setTimeout
will be executed after for
-cycle.
In addition it can be used let
:
for (let i=1; i<=11; i++) {
setTimeout(() => console.log(i), 10);
}
No comments:
Post a Comment