Hi all when i am executing this piece of code i am getting 40 in my console log can some one plese explain me why
for (var i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, 300000)
};
Hi all when i am executing this piece of code i am getting 40 in my console log can some one plese explain me why
for (var i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, 300000)
};
What you are getting on the console is the id
returned by setTimeout()
. If you run that code again you might get different value. We cannot predict this id
, it is random.
If you want to print the values from 0-9 using setTimeout()
, you need to take care of scope.
Using bind()
:
console.log('before loop');
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(this.i);
}.bind({
i: i
}), 1000)
}
console.log('after loop');
Using closures:
console.log('before loop');
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log(i); //<-- parameter i
}, 1000);
})(i); //<-- i from loop scope
}
console.log('after loop');
Print in increasing order of timeout.
console.log('before loop');
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(this.i);
}.bind({
i: i
}), 100 * i); //<-- note `* i`
}
console.log('after loop');
Your code will print 10 after 300.000 milliseconds.
Try setting it to a shorter period and you will see 10 printed.
What you probably see is linenumber in the console.
when I am executing this piece of code I am getting 40 in my console log
The reason is that setTimeout()
moves the function from the execution queue, it will only be invoked after JavaScript has finished with the current execution queue.
Understanding JavaScript Timers