Link to home
Start Free TrialLog in
Avatar of efratb
efratb

asked on

Sleep / Wait in Javascript

Hi,

I want to wait few seconds between 2 operations in javascript.
Is there a way to do it (something like sleep in Java or wait in c)?

I'm using the setTimeout(), but the problem is that sometimes I have problems with timeout intervals that are bigger than 600 ms. (Have any idea why?)

Thanks,
Efrat  
Avatar of T-Rex
T-Rex

setTimeout('action()',2000);

2000 is two seconds

Greetz,
T-Rex
ASKER CERTIFIED SOLUTION
Avatar of hongjun
hongjun
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of efratb

ASKER

Hi,

Thanks for the quick response, but as I mentioned in the question, sometimes when I use big intervals (more than 600 ms) I don't get to the timer function. Only if I lower the interval time the action is being performed.
It is quite strange as to what you are encountering. 500ms is not even 1 sec. Post your code here.

hongjun
Avatar of efratb

ASKER

Hi Hongjun,

I used to activate the actions after a button was pressed from the onClick command.
(For example: onClick="javascript:stat(); window.setTimeout('openGraph()', 2000);"

Your example made me try something a bit different:  
From the onClick I call only to the stat function and from there I call the setTimeout.
I don't understand why, but it worked! (Do you have any idea why?)

Anyway, the points are yours...
Thanks very much for your help,
I don't know if this will still be useful to you or not:

When you run stat(); javascript executes the function and only once the function has finished will it wait 2 seconds before calling openGraph(). So what happens is this:

run stat()....stat() finished.
wait 2 seconds.
run openGraph().... openGraph() finished.

And this is why you never got to see the openGraph function run while stat was running.

I can also tell you why it works after you've inserted the openGraph() call inside of the stat() call: Remember that when you call a function (like stat()) javascript will wait for that function to finish before continuing. However when you say window.setTimeout(blah(),2000) then javascript will remember to run the blah function after 2 seconds -- and instead of waiting right there it continues running the remaining lines of code!

So in your new code this is happening:

run stat(), run openGraph() after 2 seconds but continue running stat()...

After 2 seconds both functions will be running at the same time!!

Hope that solved the mystery for you (assuming you ever read this again).
Just for completeness check out this site. It Implements a sleep function in JavaScript in a couple different ways. This site shows why it is not possible to create a true sleep function in JavaScript (at least not one that will work on all popular browsers).

http://www.devcheater.com - javascript sleep