File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes HTML, CSS and JavaScript and the fly likes wait/sleep in javascript does not work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "wait/sleep in javascript does not work" Watch "wait/sleep in javascript does not work" New topic

wait/sleep in javascript does not work

Michael L. Zhang
Ranch Hand

Joined: Jul 06, 2003
Posts: 33
In a situation, we need let the javascript thread wait until another javascript function "testGetValue" becomes ready. The fuction "testGetValue" will only be ready after one java applet sets a status value to be true.

I tried to use different ways, but it never works. If I use the below function pausems() to wait, the other function will never have a chance to run during the waiting. It seems the current javascript thread blocks the other javascript thread's execution.

Then, I tried to use setTimeout as below. I do not want the below function getValueByContent return any value unless it gets the right value when testGetValue is ready.But it seems the setTimeout() launches a separate thread and do not make the main function wait or sleep at all. As a result, the function getValueByContent() will return immediately when it is being executed at the first time regardless the testGetValue is ready or not.

Can I have a way to make the javascript wait, and do not prevent the other javascirpt threads from running during waiting?

Eric Pascarello

Joined: Nov 08, 2001
Posts: 15385
JavaScript has no such thing as threads. If you do a loop you will freeze the browser.

What you need to do is learn OO javascript.

I do not have time to write an example since I am about to pass out on my keyboard.

Yuriy Fuksenko
Ranch Hand

Joined: Feb 02, 2001
Posts: 413
the simpliest way for you would be to break original function with a wait operation in the middle into 2 functions.
I mean if you have this a function looking like that:

than you should get something like:

than your "start wait process" function will look like

To make this function better, instead of hardcoding call to x2, you can pass it as a parameter.

The problem with this code though would be transfer of variables from x1 to x2. You have couple choices there, for example, you can have all variables defined in x1 and needed in x2:
1. declared as global
2. have an object declared as global, that contains all the variables.
3. have an object, that contains both functions and a variables.
but that would be up to you.
I agree. Here's the link:
subject: wait/sleep in javascript does not work
It's not a secret anymore!