title: Wait for an element to load javascript
body: <p>I am interacting with the webpage through chrome extension. I want to wait until an element (like a popup) comes up before continuing the interaction. I want to stop the execution of the function until the element appears because I am doing interacting in a sequential flow.
  Below is the example function I created. This function is not working as intended. It only delays the first iteration of the loop and the rest of the iterations of the loop are instant. So, the max time this function wait is 100ms as of now. How can I either fix this function or define an elegant way to wait.</p>
  <pre><code>function waitUntilElementLoad(elem,  maxWaitInSec) {
      for (let i = 0; i &lt; maxWaitInSec *10; i++) {
          if(elem) { return true;}
          setTimeout(() =&gt; {console.log(i);}, 100);
        }
        return false;
  }
  </code></pre>
  <p>Attempt2: (Following up on comments and answers)</p>
  <pre><code>async function waitUntilElementLoad(elem,  maxWait) {
      for (let i = 0; i &lt; maxWait*10; i++) {
          if(elem) { return true;}
          console.log(i);
          await timer(100); // then the created Promise can be awaited
      }
      return false;
  }
  
  
   if (await waitUntilElementLoad(popUpElemNextButton, 5)) {
              console.log(&quot;Popup button appeared&quot;)
   } else {
              console.log(&quot;Popup button not appeared&quot;)
   }
  </code></pre>
  <p>The waitUntilElementLoad function returns false even if the elements load up in 1 sec and the waiting time is 5 sec. If the element is already there before calling the function. it returns true. Could it be that the function does not receive updated DOM during its processing? Is there a way to handle this?</p>