0

Possible Duplicate:
Sleep in Javascript

i am writing div dynamically using javascript.

i need a delay time for writing one div to another div.

am using for loop to write a div dynamically.

sleep function not working..

my code like,

for(i=0;i<10;i++){
   sleep(100);
   $("#"+i).html("hi"+i);
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
1
  • i think instead of break you should use continue Commented Jan 19, 2013 at 10:40

5 Answers 5

3

You could use setTimeout().

Do a google search and you'll see lots of example usages.

Sign up to request clarification or add additional context in comments.

3 Comments

where can i use setTimeout()..?
first I suggest you find out how it works... and then figure out how to implement into your code. If you understand it yourself it's much better than someone simply giving you the code.
2

You need to use the getTimeout function, which takes a callback and a number of milliseconds to wait before calling it.

for(i=0;i<10;i++){
    setTimeout((function(i) {
        return function() {
            $("#"+i).html("hi"+i);
        };
    })(i), 100) 
}

3 Comments

1) Typo: it's setTimeout. 2) Classic bug: this will fire $("#10").html("hi10"); 10 times, since i changes before the function is called.
Yes, you're right. See edit.
Good work with the quick fix!
0

Use setInterval(function, miliseconds)

Comments

0

As previously suggested, use setTimeout(). You have details here.

3 Comments

An alternative that does not suck?
0

Another way to use setTimeout, using it in a inner function:

function writeDivs() {
  var i = 0;
  var divsToCreate = 100;
  var timeToSleep = 100;
  var createOneDiv = function () {
    if (i < divsToCreate) {
      $("#"+i).html("hi"+i);
      i++;
      setTimeout(createOneDiv, timeToSleep);
    }
  }
  setTimeout(createOneDiv, timeToSleep);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.