title: Using setTimeout to run a large task without blocking input, and using Promise to find out when the task is complete
body: <p>Currently, I have a function which is called to do a large task using many setTimeout's in order to not block page interaction.</p>
  
  <p>Example code follows</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function runAsync(maxMs, throttle, func){
    var begin = window.performance.now();
    var cont = func(throttle);
    var end = window.performance.now();
    if (cont){
      var newThrottle = Math.ceil((throttle/(end-begin))*maxMs);
      setTimeout(function(){
        runAsync(maxMs, newThrottle, func);
      }, 0);
    }
  }
  
  a = 0;
  
  function makeHuge(addNum){
    var target = 1000000000;
    for (var x = 0; x &lt; Math.min(addNum, target-a); x++){
      a ++;
    }
    $('#result').text(a);
    return a &lt; target;
  }
  
  $('#run').on('click', function(){
    a = 0;
    runAsync(16, 100, makeHuge);
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;span id="result"&gt;&lt;/span&gt;&lt;br/&gt;
  &lt;button id="run"&gt;Run&lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>As you can see above, setTimeout is used to do a long-running task without blocking user interaction. The called function, <code>func</code>, must return a boolean which says whether or not to continue doing the action. The throttle value is used to keep the execution time of <code>func</code> below <code>maxMs</code>, which, if set to 16, represents something like 60fps.</p>
  
  <p>However, using this setup, I cannot figure out how to incorporate the new Promises to let me know when the <code>runAsync</code> task is finished, or if it failed.</p>