Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created December 23, 2016 04:59
Show Gist options
  • Select an option

  • Save threepointone/8058f64cf47decd025171014bd3aeb2d to your computer and use it in GitHub Desktop.

Select an option

Save threepointone/8058f64cf47decd025171014bd3aeb2d to your computer and use it in GitHub Desktop.

Revisions

  1. threepointone created this gist Dec 23, 2016.
    42 changes: 42 additions & 0 deletions gen-ric.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    // 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)