Created
December 23, 2016 04:59
-
-
Save threepointone/8058f64cf47decd025171014bd3aeb2d to your computer and use it in GitHub Desktop.
generators + requestIdleCallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is a generic runner for iterators | |
// for every yield, it checks to see if any time is remaining | |
// on the idle loop, and executes more work if so. | |
// else, it queues up for the next idle period | |
function go(it, callback){ | |
requestIdleCallback(deadline => { | |
let val = it.next() | |
while(!val.done){ | |
if(deadline.timeRemaining() <= 0){ | |
go(it, callback) | |
return | |
} | |
val = it.next() | |
} | |
callback(val.value) | |
}) | |
} | |
// this is a function that sums all numbers up to a given number | |
// written as a generator, it yields every 1000 steps, | |
// but you can adjust that as you please | |
// yielding more often introduces overhead, | |
// while less often might block thread | |
function* summation(x){ | |
let i = x, ret = 1 | |
while(i>1){ | |
ret += i | |
i-- | |
if(i%1000 === 0) yield | |
} | |
return ret | |
} | |
// delay for a second before starting to get clean stats | |
setTimeout(function(){ | |
console.profile() | |
go(summation(1000000), result => { | |
console.log(result) | |
console.profileEnd() | |
}) | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmmmm nice idea, had fun going a bit further :)
https://jsfiddle.net/4L6n0qwy/4/