Currently, I have a function which is called to do a large task using many setTimeout's in order to not block page interaction.
Example code follows
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 < Math.min(addNum, target-a); x++){
a ++;
}
$('#result').text(a);
return a < target;
}
$('#run').on('click', function(){
a = 0;
runAsync(16, 100, makeHuge);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="result"></span><br/>
<button id="run">Run</button>
As you can see above, setTimeout is used to do a long-running task without blocking user interaction. The called function, func
, 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 func
below maxMs
, which, if set to 16, represents something like 60fps.
However, using this setup, I cannot figure out how to incorporate the new Promises to let me know when the runAsync
task is finished, or if it failed.