Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created December 23, 2016 04:59
Show Gist options
  • Save threepointone/8058f64cf47decd025171014bd3aeb2d to your computer and use it in GitHub Desktop.
Save threepointone/8058f64cf47decd025171014bd3aeb2d to your computer and use it in GitHub Desktop.
generators + requestIdleCallback
// 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)
@slorber
Copy link

slorber commented Dec 29, 2016

Hmmmm nice idea, had fun going a bit further :)

https://jsfiddle.net/4L6n0qwy/4/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment