-2

I want most understandable syntax for polling a flag and return when it is true, my code snippet below doesn't work I know, what's the syntax that would make it work if you get my idea ?

async function watch(flag) {
    let id = setInterval(function(){
        if (flag === true) {
            clearInterval(id);
        }
    }, 1000);
    return flag;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

3
  • If you want to poll a variable where the value is a primative, then you need to define it outside the function, otherwise it can't change.
  • If you want to have a promise resolve when that condition is done, then you have to create it explicitly. async and await are tools for managing existing promises.

let flag = false;

function watchFlag() {
  return new Promise(resolve => {
    let i = setInterval(() => {
      console.log("Polling…");
      if (flag) {
        resolve();
        clearInterval(i);
      }
    }, 500);
  });
}

setTimeout(() => {
  flag = true;
}, 1500);

console.log("Watching the flag");

watchFlag().then(() => {
  console.log("The flag has changed");
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

If you don't know when the flag is going to change (in 10 seconds or in 10 minutes), you can use a setter instead. Probably an anti-pattern, but again your question doesn't really show us how you would be using this flag in your code.

const flagsObject = {
  set flag(stat) {
    this._flag = stat;
    if (stat) {
        // call the function you need to call when flag is true 
        // you could add additional condition if you only want to run the function 
        // when the flag is switched
        doSomething()
    }
  },
  get flag() {
    return this._flag;
  }
};

flagsObject.flag = true; // doSomething() will be called
alt146
  • 501
  • 6
  • 7