Skip to content

Instantly share code, notes, and snippets.

@tusharmath
Created October 4, 2018 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tusharmath/af40e0460ddf51c083c52d253845d03f to your computer and use it in GitHub Desktop.
Save tusharmath/af40e0460ddf51c083c52d253845d03f to your computer and use it in GitHub Desktop.
Run Tasks in Batch
interface Task {
(): void
}
interface IdleCallback {
timeRemaining(): number
}
declare function requestIdleCallback(cb: (id: IdleCallback) => void): number
function batch() {
const taskQueue = new Array<Task>()
let scheduled = false
function run(id: IdleCallback) {
scheduled = false
while (id.timeRemaining() > 0 && taskQueue.length > 0) {
const task = taskQueue.shift()
if (task) task()
}
schedule()
}
function schedule() {
if (!scheduled && taskQueue.length > 0) {
scheduled = true
requestIdleCallback(run)
}
}
return (task: Task) {
taskQueue.push(task)
schedule()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment