Skip to content Skip to sidebar Skip to footer

Javascript Return Value From Settimeout

I want do something like that: var x = function(){ if (controlVar === 0) { setTimeout(x, 300); } else { return value; }; Is there a method in js for call a function

Solution 1:

Is there a method in js for call a function like in synchronous code (var z = x()) and return a value only when my controlVar turn in 1?

No. Assignment is synchronous. It can't wait for an asynchronous function. To be more precise, x immediately returns, it doesn't wait for the timeout.

setTimeout simply adds a new job to the job queue. Only after the current job is finished, the next job will be processed.

I want call a recursive function that return only when a variable that act like a semaphore turn green.

That doesn't work in JavaScript because it has the concept of "run to completion":

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.

Going back to your example, we start with evaluating the script and calling x. This is the current status the job queue:

Job Queue--------------------------------------------------+
| +---------------------+                                  |
| |What: evaluate script|                                  |
| |                     |                                  |
| |                     |                                  |
| +---------------------+                                  |
+----------------------------------------------------------+

When the line setTimeout(x, 300); is executed, a new entry is added to the job queue:

Job Queue--------------------------------------------------+|+---------------------+    +-----------------+           |||What: evaluate script||What: execute x  ||||||When: 300ms      |||||||||+---------------------+    +-----------------+           |+----------------------------------------------------------+

In order for the the next entry to be processed, the current job must be completed first. That means, since we are currently calling x, x must terminate. Only after x returned, the event loop can move on to the next job and call x again.

Hopefully this makes it a bit clearer why x cannot wait for the timeout.


For alternative solutions see How do I return the response from an asynchronous call? .

Post a Comment for "Javascript Return Value From Settimeout"