Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Created February 23, 2018 08:20
Show Gist options
  • Save smashingpat/46c6ec5e3859497d4f553eb05e3e03a9 to your computer and use it in GitHub Desktop.
Save smashingpat/46c6ec5e3859497d4f553eb05e3e03a9 to your computer and use it in GitHub Desktop.
timer
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)
}
})
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