Skip to content

Instantly share code, notes, and snippets.

@raohmaru
Last active January 28, 2024 19:04
Show Gist options
  • Save raohmaru/af6c2f86b7214627f049ae1ba52981ba to your computer and use it in GitHub Desktop.
Save raohmaru/af6c2f86b7214627f049ae1ba52981ba to your computer and use it in GitHub Desktop.
requestAnimationFrame() in node.js
const callbacks = [];
const fpsInterval = 1000 / 60;
let time = performance.now();
function requestAnimationFrameLoop() {
const now = performance.now();
const delta = now - time;
if (delta >= fpsInterval) {
// Adjust next execution time in case this loop took longer to execute
time = now - (delta % fpsInterval);
// Clone array in case callbacks pushes more functions to it
const funcs = callbacks.slice();
callbacks.length = 0;
for (let i = 0; i < funcs.length; i++) {
funcs[i] && funcs[i](now, delta);
}
} else {
setImmediate(requestAnimationFrameLoop);
}
}
function requestAnimationFrame(func) {
callbacks.push(func);
if (callbacks.length === 1) {
setImmediate(requestAnimationFrameLoop);
}
return callbacks.length - 1;
}
function cancelAnimationFrame(id) {
callbacks[id] = undefined;
}
@raohmaru
Copy link
Author

Polyfill of requestAnimationFrame() for node.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment