开发者

javascript show in cycle with delay

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开发者_StackOverflow't work... I guess there's should be using closures..


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


Should do the job:

for (var i = 0; i < 10; ++i) {
  (function(i) {
     setTimeout(function(){console.log(i);}, i*300);
  })(i);
}


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜