1

So that I could use a loop, and have it pause, say 250 ms after each iteration? [ without setTimeout or setInterval?]

Edit: Ok, so I have a for loop that uses AJAX to post data ($.ajax()) . It has lots of vars in it, like data: 'uid=' + uid, + '&othervars=' + morevars etc, and each loop, the variables change.. so If put that [huge] part into a function() {} [Inside of a setTimeout(), using a counter in the loop to increment the timeout], when it executes, will the actual value be in place where I put the vars?

Matt
  • 2,462
  • 6
  • 21
  • 34
  • You can create your own sleep() subroutine that takes care of all those details for you, and you could even support a parameter (I suggest making it _optional_ and default to 1 second if no parameter was provided). –  Jun 29 '11 at 03:13
  • How? I don't know what subroutine is – Matt Jun 30 '11 at 15:16
  • Lots of results here on SO already: http://stackoverflow.com/search?q=javascript+sleep – Wesley Murch Jun 30 '11 at 16:51
  • possible duplicate of [Sleep in javascript - no setTimeout](http://stackoverflow.com/questions/6484321/sleep-in-javascript-no-settimeout) – Wesley Murch Jun 30 '11 at 16:53
  • why don't you want to use setTimeout or setInterval? – Matt Jun 30 '11 at 16:53
  • @Matt, because the code I've written would be a lot easier if I could just add one line [in the loop]: sleep(1000); – Matt Jun 30 '11 at 17:08

2 Answers2

8

Current browser implementations are essentially single-threaded, so sleeping in your code will likely block the entire UI. It's not what you want, and just plain isn't how JS works. Refactor your code so that you can use setTimeout.

Matti Virkkunen
  • 58,926
  • 7
  • 111
  • 152
0

You will need to use one of javascript's timer functions (setTimeout or setInterval).

There is no real way around them.

Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295