Last active
November 6, 2022 07:34
-
-
Save gordonbrander/5120694 to your computer and use it in GitHub Desktop.
FPS Reduce -- a stream of times to use as an alternative to event loops.
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
var reducible = require("reducible/reducible"); | |
var isReduced = require("reducible/is-reduced"); | |
function fps(desiredFps) { | |
// Create a stream of times to use as an event loop with | |
// https://github.com/Gozala/coreduction/blob/master/coreduction.js | |
// Number -> Reducible[Float time, Float time, ...] | |
// Convert seconds to milliseconds. | |
var msPerFrame = 1000 / desiredFps | |
return reducible(function reduceFps(next, result) { | |
function tick() { | |
// Pass current time to `next()`, and accumulate result. | |
result = next(Date.now(), result); | |
// If value has not been reduced, set a timer to go again. | |
if(!isReduced(result)) setTimeout(tick, msPerFrame); | |
} | |
tick(); | |
}) | |
} | |
module.exports = fps; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment