Created
July 16, 2020 19:08
-
-
Save UpperCod/7168837bbe3fa5d7d3394a13d331bdd9 to your computer and use it in GitHub Desktop.
Small script to optimize concurrency in browsers, ideal for handling concurrent animations between 55fps to 60fps
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
let task = []; | |
let inLoop; | |
let loopTask = () => { | |
let currentTask = task; | |
task = []; | |
let fn; | |
let start = performance.now(); | |
while ((fn = currentTask.pop())) { | |
let now = performance.now(); | |
if (now - start < 8) { | |
fn(); | |
} else { | |
task = currentTask.concat(task); | |
break; | |
} | |
} | |
if (task.length) { | |
setTimeout(loopTask); | |
} else { | |
inLoop = false; | |
} | |
}; | |
let addTask = (fn) => { | |
if (!task.includes(fn)) { | |
task.push(fn); | |
} | |
if (!inLoop) { | |
inLoop = true; | |
Promise.resolve().then(loopTask); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment