Created
October 4, 2018 14:21
-
-
Save tusharmath/af40e0460ddf51c083c52d253845d03f to your computer and use it in GitHub Desktop.
Run Tasks in Batch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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