Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wait/sleep in javascript does not work

 
Michael L. Zhang
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Eric
 
Yuriy Fuksenko
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic