javascriptasync-awaitsetintervalclearinterval

javascript async and setInterval for polling


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;
}

Solution

  • 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");
    });