0
votes

I have this javascript method:

function waitcheck(){
        if(wait == 0){
            offlineUpload()
        }
        else{
            setTimeout(waitcheck(), 2000)
        }
    }

I'm lost, right now I'm getting an error saying "Maximum stack size exceeded"

The goal of this method is to wait until a var is turned into "0" by an async function.

Is there a better way to do this?
How can I get around this error?

3

3 Answers

4
votes

You're calling the waitcheck function recursively, instead of passing the function into setTimeout.

Do this in your else:

setTimeout(waitcheck, 2000)

Assuming your wait global is set correctly outside of this function, your code should work.

1
votes

This is the textbook example where to use setInterval

This will execute your checker function every 2 seconds and stop when wait is 0.

var interval = setInterval(function() {
  if(wait === 0){
    clearInterval(interval);
    offlineUpload();
  }
}, 2000);
0
votes

Remove the parentheses on the function name. (They're causing that function to be called, instead of passing it as a reference.)

Like so:

function waitcheck(){
        if(wait == 0){
            offlineUpload()
        }
        else{
            setTimeout(waitcheck, 2000)
        }
    }