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);
  }
})();
4
  • @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 ? Commented Jan 30, 2014 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. Commented Jan 30, 2014 at 19:11
  • stackoverflow.com/questions/5226285/… Commented Jan 30, 2014 at 19:17
  • why is my question rated Negative ? Commented Jan 30, 2014 at 20:08

3 Answers 3

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 );
Sign up to request clarification or add additional context in comments.

7 Comments

are you sure this will print the numbers to the console with a interval of 1000ms ?
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.
your comment is pretty close can you please elaborate it as i can understand it
@Constantine don't forget to accept answers if they was helpful and welcome to SO ;) Cheers.
i am sorry i dont have enough rank to rate up your comments
|
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);

5 Comments

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
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 ?
The first parameter of setTimeout must be a function or a string that will be evaled
what about setTimeout(test(i),1000); function test(i) { return i; }
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
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);.

1 Comment

i guess then it should make a delay 1000ms between logging the values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.