Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait with setTimeout until a variable get loaded and, at the same time, receive HTTP requests!

I' ve made a in JavaScript function to check every 100 ms if a global variable is loaded. When the variable will be loaded the function will return the value of the variable as shown below. In my code I use an HTTP server in JavaScript, and the variable will be loaded when a specific HTTP request with specific headers arrive to my server.

function checkVariable()
{
    if ( myvar != null )
    {
            return myVar;
    }
    else
    {
            window.setTimeout("checkVariable();",100);
    }
} 

I use this function in a piece of code like this:

// arithmetis operations... [1]

myVar = checkVariable();

// arithmetic operations that use myVar [2]

myVar is initiated with null. The problem is that the arithmetic operations in [2] are done before myVar got its value. Instead, I want my code to wait until myVar get its value, and then to continue with the operations.

Before trying the setTimeout function, I tried to make the code waiting using a while loop, but the problem then was that the HTTP server couldn't receive any HTTP request due to the continuously execution of the while loop!

Could someone help me to solve this problem?

Thank you in advance!

like image 274
Thanasis Petsas Avatar asked Jul 11 '10 18:07

Thanasis Petsas


People also ask

Does setTimeout work synchronously?

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

How do you wait for setTimeout?

Wait with setTimeout Therefore, setTimeout makes the console. log only fire after 1000 milliseconds (1 second) of the second console. log call. There you go, one of the ways to delay the code execution is by using setTimeout.

Does setTimeout execute immediately?

Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

How many times does setTimeout () execute the function parameter?

The JS setTimeout() method will call a function after the time specified in milliseconds (1000 ms = 1 second) has passed. The specified function will be executed once.


1 Answers

I would probably make the remaining arithmetric operations a callback. Something like:

function checkVariable()
{
    if ( myvar != null )
    {
            computeVariable(myVar);
    }
    else
    {
            window.setTimeout("checkVariable();",100);
    }
} 

Then:

// arithmetis operations... [1]

myVar = checkVariable();

function computeVariable(myVar) {
  // arithmetic operations that use myVar [2]
}
like image 126
jpoz Avatar answered Oct 19 '22 04:10

jpoz