The javascript method window.requestAnimationFrame(callback)
will call your callback function on the next animation frame. It's commonly used for animation, and will probably work well for what you're doing.
To modify your code to use requestAnimationFrame
, you have to make your function print a small chunk on its own, with a reference to know what chunk to print. If you stored your page contents in an array, for example, that could just be a starting index and a length. Since you are printing the increasing powers of 2, you can just pass in the last power of two and the number of lines you want to print for each run of the function.
You'll also need an exit condition -- a check within limits
that if true, returns without requesting the next frame. I simply put a hard cap on the value of a
, but you could also check that the index is less than array length (for my array of page contents idea above).
Because requestAnimationFrame
passes in a function name as a callback, you can't pass arguments into it. Therefore, you have to use bind
to sort of attach the values to the function. Then, within the function, you can access them using this
. config
is just an object to hold the initial arguments you want the function to have, and then you bind it, which allows you to access them within the function with this.numLines
and this.a
.
Then, when you request the next frame, you have to bind the values to limits
again. If you are alright with keeping the arguments the same, you can just do limits.bind(this)
. But if you want to change them, you can create another object in a similar way to how I wrote config
and bind that instead.
The following code seems to be a basic example of roughly what you're looking for:
var foo = document.getElementById('foo');
var maxA = 1000000000000000000000000000000000;
function limits() {
for(var i=0; i<this.numLines; ++i) {
foo.innerHTML += "<p>" + this.a + "</p>";
this.a *= 2;
if(this.a > maxA) {
return;
}
}
requestAnimationFrame(limits.bind(this));
}
config = {
numLines: 3,
a: 1
};
requestAnimationFrame(limits.bind(config));
And is implemented in JSFiddle here. I've also implemented a version where it puts each line at the top of the page (as opposed to appending it to the bottom), so that you can see it happening better (you can find that one here).