Created
February 23, 2018 08:20
-
-
Save smashingpat/46c6ec5e3859497d4f553eb05e3e03a9 to your computer and use it in GitHub Desktop.
timer
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
import { withTimer } from './with-timer' | |
withTimer(() => { | |
const c = document.createElement('canvas') | |
document.body.appendChild(c) | |
const cc = c.getContext('2d') | |
let hue = 0 | |
return () => { | |
hue++ | |
cc.fillStyle = `hsl(${hue}, 50%, 50%` | |
cc.fillRect(0, 0, c.width, c.height) | |
} | |
}) |
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
export function withTimer(drawMethod) { | |
const update = drawMethod() | |
const fps = 30 | |
const deltaTime = 1000/fps | |
let accumulatedTime = 0 | |
let lastTime = performance.now() | |
function enqueue(time = performance.now()) { | |
accumulatedTime += (time - lastTime) | |
while (accumulatedTime > deltaTime) { | |
update(deltaTime) | |
accumulatedTime -= deltaTime | |
} | |
lastTime = time | |
requestAnimationFrame(enqueue) | |
} | |
enqueue() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment