Reputation: 99
can anyone please help me to figure out what this code javaScript code means
(function(){
for(var i=0;i<5;i++){
setTimeout(console.log(i),1000);
}
})();
Upvotes: 0
Views: 59
Reputation: 27765
You have run into very common closure issue. To fix this you can have for example self invoked function. Also you should pass function handler to setTimeout
instead of invoking console.log
:
for(var i=0;i<5;i++){
(function( i ) {
setTimeout( function( ) {
console.log(i);
},1000);
})( i );
}
If you want to print to console numbers from 0 to 4 in 1000ms interval you should use setInterval
function:
var intervalHandler = null
, i = 0;
intervalHandler = setInterval( function() {
console.log( i );
if( i === 4 ) {
clearInterval( intervalHandler );
return;
}
i++;
}, 1000 );
Upvotes: 2
Reputation: 10849
Your code basically calls a function which is gonna log
0
1
2
3
4
A single time, why ? Because setTimeout is actually running setTimeout(undefined, 1000)
5 times, according to the return value of console.log
, it will not evaluate a function, so the instruction is just lost.
Though from what I understand of what the code tries to say, to make the code work well, you could delegate the iteration control to a self calling function delayed with setSimeout
(function self(times, delay) {
self.config = self.config || {
times: times,
delay: delay,
iteration: 0
};
++self.config.iteration;
if (self.config.iteration <= self.config.times) {
console.log(self.config.iteration);
setTimeout(self, self.config.delay);
}
})(5, 1000);
Upvotes: 1
Reputation: 390
for(var i=0;i<5;i++)
//this code loop for five time before it break.
i.e, it will execute this function for five time setTimeout(console.log(i),1000);
.
setTimeout() is a javascript function for delay and it going to delayed for 1s and it going to carry out action for console.log(i);
.
Upvotes: 0