DEV Community

Discussion on: The Million.js Manifesto

 
miketalbot profile image
Mike Talbot ⭐

Yeah you don't need js-coroutines itself, just some of the techniques. I'd be interested in thinking through it with you and seeing if I can help. js-coroutines is a load of helper functions for common operations wrapped around a very simple core.

export async function run(
    coroutine,
    loopWhileMsRemains = 1,
    timeout = 16 * 10
) {
    const options = {timeout}
    let terminated = false
    let resolver = null
    const result = new Promise(function (resolve, reject) {
        resolver = resolve
        const iterator = coroutine()
        window.requestIdleCallback(run)

        function run(api) {
            if (terminated) {
                iterator.return()
                return
            }
            const minTime = Math.max(0.5, loopWhileMsRemains)
            try {
                do {
                    const {value, done} = iterator.next()
                    if (done) {
                        resolve(value)
                        return
                    }
                    if (value === true) {
                        break
                    }
                } while (api.timeRemaining() > minTime)
            } catch (e) {
                reject(e)
                return
            }

            window.requestIdleCallback(run, options)
        }
    })
    result.terminate = function (result) {
        terminated = true
        if (resolver) {
            resolver.resolve(result)
        }
    }
    return result
}
Enter fullscreen mode Exit fullscreen mode

The idea of deciding on the importance of a particular update and adding it to some queues that then either get immediate updates (user input) or more casual updates that could be run in priority queues on idle seems like a plan.