D
D
Demigodd2018-09-28 08:04:17
JavaScript
Demigodd, 2018-09-28 08:04:17

How to change the value of a variable after recursive setTimeout calls have finished?

variable = false;

function aaa() {
  bbb();
  variable = true;
}

function bbb() {
  if(//expression exit) return;
  SetTimeout(bbb, 2000);
}

aaa();  // call main function

The fact is that if you call the 1st function, it will call the 2nd one and without waiting, it will make the variable variable = true ;
What are some ways to wait for the bbb functions to execute and then make the variable true ?
It's just that the recursive call of the 2nd function is random, it can be called 5, 10 or 20 times.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-09-28
@Demigodd

You don't seem to understand asynchronous work in JS. The SetTimeout function does not wait for the specified time (you have 2 seconds). She sets the timer and returns immediately. The function specified in SetTimeout after the specified time will be queued for JS calls and launched when the queue reaches it.
Thus, the function bbb called from aaa will complete almost immediately. You can write like this:

function bbb() {
  if(...) {
    variable = true;
    return;
  }
  SetTimeout(bbb, 2000);
}

But the variable will change only when the condition is triggered, when the aaa function has long been completed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question