Skip to content

Instantly share code, notes, and snippets.

@UpperCod
Created July 16, 2020 19:08
Show Gist options
  • Save UpperCod/7168837bbe3fa5d7d3394a13d331bdd9 to your computer and use it in GitHub Desktop.
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
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