views:

38

answers:

3

Simple example:

for (var i = 0; i < 10; ++i) {
  console.log(i); // <--- should be show with delay in 300ms 
}

Simple setTimeout using of course doesn't work... I guess there's should be using closures..

+6  A: 

It's a simple matter of writing a recursive function:

function display(i)
{
  if (i == 10) return;    
  setTimeout(function(){ console.log(i); display(i+1); }, 300);
}
Victor Nicollet
I would suggest to add second parameter let's say n and then replace the if statement with: "if (i==n)". Just as matter of genericity.
Artem Barger
As a matter of genericity, I would go as far as provide the traditional for-loop arguments : initialization, step function and condition function: function recurse(init, condition, step) { if (condition(init)) recurse(step(init), condition, step); }
Victor Nicollet
Completely right ;)
Artem Barger
+2  A: 

You could use setInterval, like so:

var i = 0;
var id = setInterval(function(){
    if (i == 9) clearInterval(id);
    console.log(i);
    i++;
}, 300);

Example here http://jsfiddle.net/MLWgG/2/

Castrohenge
+3  A: 

Should do the job:

for (var i = 0; i < 10; ++i) {
  (function(i) {
     setTimeout(function(){console.log(i);}, i*300);
  })(i);
}
Artem Barger
Or `(i+1)*300` depending on whether the first `i` should be printed immediately or not.
Felix Kling
Ha!!! Amazing! i*300 was missed. Thanks!
Alex Ivasyuv
@Alex, welcome.
Artem Barger