Last active
January 28, 2024 19:04
-
-
Save raohmaru/af6c2f86b7214627f049ae1ba52981ba to your computer and use it in GitHub Desktop.
requestAnimationFrame() in node.js
This file contains 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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Polyfill of requestAnimationFrame() for node.js.