Tutorial :javascript show in cycle with delay



Question:

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


Solution:1

Should do the job:

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


Solution:2

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


Solution:3

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/


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »