April 7, 2012

How to create pause or delay in FOR loop?

Question by jams

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or jQuery

This is a test example

 var s = document.getElementById("div1");
 for (i = 0; i < 10; i++) {
     s.innerHTML = s.innerHTML + i.toString();
     //create a pause of 2 seconds.
  }

Answer by jams

I tried all one, but I think this code is better one, it is very simple code.

var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString();  i++;}, 2000);

Answer by Starx

This is how you should do it

var i = 0;
setTimeout(function() {
   s.innerHTML = s.innerHTML + i.toString();
   i++;
},2000);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!