title: wait for loop to finish populating array before executing next function
body: <p>I am trying to access <code>imgArr</code> after this loop, of course I get am empty Array because <code>console.log(imgArr)</code> is executed synchronously with the for loop.
  But I need <code>imgArr</code> to be populated in order to be used in other logic.
  I can't use setTimeout again because because I can't know how much time is needed for the loop to be completed.
  I tried to wrap all of this inside a function and call it inside another function, but to no avail</p>
  <pre><code>var imgArr = []
  var nextBtn = document.querySelector('[aria-label=&quot;Next&quot;]')
  for (var i = 0; i &lt; 15; i++) {
      setTimeout(() =&gt; {
          if (nextBtn) {
              Object.values(document.querySelectorAll('img')).map(img =&gt; {
                  if (imgArr.indexOf(img.src) === -1) imgArr.push(img.src)
              });
              nextBtn.click();
              nextBtn = document.querySelector('[aria-label=&quot;Next&quot;]');
          };
      }, i * 1000);
  };
  console.log(imgArr) // expected: [], needed: [element1, element2, ...]
  </code></pre>