title: Javascript wait for condition to be true using promises
body: <p>I am struggling to make a simple waiting function in my program. I want to use promises and async await if possible. What I have so far:</p>
  
  <pre><code> function waitForCondition(conditionObj) {
     var start_time = new Date().getTime()
  
     function checkFlag() {
       if (conditionObj.arg == conditionObj.test) {
         console.log('met');
         return new Promise(resolve =&gt; setTimeout(resolve, 1));
       } else if (new Date() &gt; start_time + 3000) {
         console.log('not met, time out');
         return new Promise(resolve =&gt; setTimeout(resolve, 1));
       } else {
         window.setTimeout(checkFlag, 1000); 
       }
     }
     checkFlag();
   }
  
    async function run() {
      console.log('before');
      await waitForCondition({arg: '1', test: '1'})
      console.log('after');
    }
    run();
  </code></pre>
  
  <p>It should check every 1 second for a maximum time of 3 seconds. The console should look like this:</p>
  
  <pre><code>'before'
  'met'
  'after'
  </code></pre>