0

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);
  }
})();
Constantine
  • 99
  • 1
  • 10
  • @clentfort do you think that is gonna define the reason why this code is logging the values {0,1,2,3,4,} to the console at a time instead of waiting for 1000ms as defined in setTimeout ? – Constantine Jan 30 '14 at 19:10
  • It doesn't wait for the timeout because you're passing the result of calling `console.log()` to `setTimeout` instead of passing a function. – Pointy Jan 30 '14 at 19:11
  • http://stackoverflow.com/questions/5226285/settimeout-in-a-for-loop-and-pass-i-as-value – clentfort Jan 30 '14 at 19:17
  • why is my question rated Negative ? – Constantine Jan 30 '14 at 20:08

3 Answers3

2

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 );
antyrat
  • 27,479
  • 9
  • 75
  • 76
  • are you sure this will print the numbers to the console with a interval of 1000ms ? – Constantine Jan 30 '14 at 19:22
  • This will not print them w/ interval of 1000ms, this will print them all after 1000ms. If you want to print numbers w/ interval you will need another functionality for this and probably use `setInterval` method or recursive `setTimeout`. – antyrat Jan 30 '14 at 19:24
  • your comment is pretty close can you please elaborate it as i can understand it – Constantine Jan 30 '14 at 19:29
  • @Constantine don't forget to accept answers if they was helpful and welcome to SO ;) Cheers. – antyrat Jan 30 '14 at 20:08
  • i am sorry i dont have enough rank to rate up your comments – Constantine Jan 30 '14 at 20:10
  • No, I mean accept answers. I saw you have 4 questions and non of the answers was accepted. See more info here http://stackoverflow.com/help/accepted-answer . It's check mark near the answer. – antyrat Jan 30 '14 at 20:14
  • well the only reason why i haven't accepted a single answer is that no one answer helped as i was expecting from SO, but Mr.aduch's answer is really kind of i wanted and i surely will accept it after some more comments. – Constantine Jan 30 '14 at 20:26
1

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);
axelduch
  • 10,769
  • 2
  • 31
  • 50
  • thanks 'aduch' your answer works as expected but i want to know why is not my code running or what does it means to the js engine – Constantine Jan 30 '14 at 19:33
  • your answer really defines the reason but does it mean if i replace the console.log(i) which is returning the undefined, with a function returning the value of i . the code will work as expected ? – Constantine Jan 30 '14 at 19:47
  • The first parameter of setTimeout must be a function or a string that will be evaled – axelduch Jan 30 '14 at 19:49
  • what about setTimeout(test(i),1000); function test(i) { return i; } – Constantine Jan 30 '14 at 19:51
  • 1
    `setTimeout(test(i),1000);` will not work `setTimeout(test.bind(null, i),1000);` will work because bind returns a function, but does not call it – axelduch Jan 30 '14 at 19:53
0

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);.

Constantine
  • 99
  • 1
  • 10
Segun Adeniji
  • 370
  • 5
  • 11