title: Javascript wait for Promises to return data then assign onClick event listener to perform action on returned data
body: <p><strong>(UPDATE: I'm now able to solve the issue with plotting the data by using async / await to wait for the promise to resolve... However, now I'm facing the issue with how to stop the <code>setInterval</code> timer that's in a closure.)</strong></p>
  <h3>I want to accomplish the following:</h3>
  <ul>
  <li><s>Send 10 fetch requests <em>sequentially</em> and measure response time for each request (in millisec)</s></li>
  <li><s>For each request push response time to an array</s></li>
  <li>On click of a <em>start</em> button - starts the plotting of points with a predefined function: <code>drawChart(data)</code> . The points should be added every second.</li>
  <li>On click of a <em>stop</em> button - stop the plotting.</li>
  </ul>
  <h3>onLoad event listener:</h3>
  <pre><code>window.onload = async function () {
     drawChart([]);
     const data = await fetchData(15);
     document.getElementById(&quot;start&quot;).onclick = () =&gt; plotData(data);
  
     // I want to be able to clearInterval on click of Stop button... but its not working...
     document.getElementById(&quot;stop&quot;).onclick = clearInterval(plotData);  
  };
  </code></pre>
  <h3>plot / fetch function:</h3>
  <pre><code>const plotData = (data) =&gt; {
    let i = 0;
    // How do i clear this interval outside of this function?
    const interval = setInterval( () =&gt; {
      i++;
      if (i === data.length) { clearInterval(interval); }
      let newData = data.slice(0,i);
      drawChart(newData); 
      console.log('draw');
    }, 1000);
  }
  
  const fetchData = async (times) =&gt; {
    let url = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-1295/lounging-dog.jpg`;
    const data = [];
    for (let i = 0; i &lt; times; i++) {
      start = (new Date()).getTime();
      await fetch(url)
        .then( res =&gt; {
          end = (new Date()).getTime();
          console.log('times', i+1);
          console.log('response milisec', end - start);            
          data.push({ xVal: i+1, yVal: end-start}); 
        })
        .catch( e =&gt; console.log(e));   
    }
    return data;
  };
  </code></pre>
  <p>What I can't wrap my mind about is how to clearInterval in the window context when the setInterval is defined within a callback.</p>
  <p>You can also see my <a href="https://codepen.io/alchuang/pen/wvwXrER" rel="nofollow noreferrer">CodePen</a> for more information.</p>
  <p>Thanks in advance!</p>