Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Suggestion: Include a IdleTask for simplifying some use cases of IdleQueue #3

Open
Jamesernator opened this issue Sep 21, 2018 · 0 comments

Comments

@Jamesernator
Copy link

Jamesernator commented Sep 21, 2018

Given generator's (two-way) coroutine design was designed in order to enable custom runners it would be good to have some runner built on top of IdleValue that can simplify writing.

Simple example:

const size = width * height * 4
const imageData = new Uint8Array(size)

// Just a simple whitenoise image generator
return new IdleTask(function*() {
  for (let i = 0 ; i < size ; i++) {
    // Allow scheduler to break this up as much as it needs
    yield
    imageData[i] = Math.floor(Math.random() * 256)
  }
  return imageData
})

Example implementation of IdleTask (doesn't handle things like const value = yield anotherIdleValue or other stuff like that though):

class IdleTask {
  constructor(genFunction) {
    this._job = genFunction()
    this._value = null
    this._ready = false

    const runUntilComplete = (idleDeadline) => {
      while (idleDeadline.timeRemaining() > 0) {
        const iterResult = this._job.next()
        if (iterResult.done) {
          this._ready = true
          this._value = iterResult.value
          return
        }
      }
      this._idleCallback = requestIdleCallback(runUntilComplete)
    }

    this._idleCallback = requestIdleCallback(runUntilComplete)
  }

  _runToCompletion() {
    while (true) {
      const iterResult = this._job.next()
      if (iterResult.done) {
        this._ready = true
        this._value = iterResult.value
        return this._value
      }
    }
  }

  getValue() {
    if (this._ready) {
      return this._value
    } else {
      cancelIdleCallback(this._idleCallback)
      return this._runToCompletion()
    }
  }
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant