Eric_B
Eric_B

Reputation: 149

Detecting an update to a global var in async function

I'm having trouble updating a variable to the global scope. I have declared a variable state, then when a function is complete I return the variable. This all works. However I have another function running asynchronously where I'm waiting for the var to update, but it never gets the updated state value and loops 'notReady' indefinitely. I expected "return state" to update the variable in the global scope but it doesn't. How can I get the updated global state variable to update in a previously fired function?

var state = 'notReady';

function do(state){
   // long/heavy webGL function
   state = 'ready'
   return state; //state successfully changes to 'ready'
};

$.when( do(state) ).then(function(state) {
    console.log(state); // this logs 'ready' successfully
    return state;
});


function previousFiredFunction(){
   function waitForState(){
      if(state === 'ready'){
         // do something when ready (this is never 'ready')
      } else {
         setTimeout(waitForState, 200); 
      }
   }
   waitForState();
}
previousFiredFunction();

Upvotes: 1

Views: 527

Answers (1)

David784
David784

Reputation: 7464

In your do function, you have a function argument with the same name as your global variable (state). This masks the global variable. And all "native" variables (e.g. strings and numbers) are passed by value, NOT by reference.

Simple fix, just lose the argument entirely. Then you will be working with the global variable.

var state = 'notReady';

function fndo() {
  // long/heavy webGL function
  state = 'ready'
  return state; //state successfully changes to 'ready'
};

$.when(fndo(state)).then(function (state) {
  console.log(state); // this logs 'ready' successfully
  return state;
});


function previousFiredFunction() {
  function waitForState() {
    console.log('wfs', state);
    if (state === 'ready') {
      // do something when ready (this is never 'ready')
    } else {
      setTimeout(waitForState, 200);
    }
  }
  waitForState();
}
previousFiredFunction();

Also as an aside, I'm really surprised you can get this code to run at all, since do is a keyword in JavaScript. I had to change the name to even run your code.

Upvotes: 1

Related Questions