Skip to content

Instantly share code, notes, and snippets.

@diogotito
Created June 12, 2024 11:34
Show Gist options
  • Save diogotito/2754024204aa3f0d3aba9d0860f07366 to your computer and use it in GitHub Desktop.
Save diogotito/2754024204aa3f0d3aba9d0860f07366 to your computer and use it in GitHub Desktop.
Testing requestAnimationFrame timings with `progress` as a live expression, ES6 Map and console.table
{
const SAMPLES = 1000
progressObj = {
p: 0,
target: SAMPLES,
bars: 10,
toString() {
if (this.p < this.target) {
let progressBar = [...Array(this.bars)].map((_, bar) => ((this.p) / this.target) > ((bar + 1) / this.bars) ? '#' : '.').join('')
let percent = ((this.p) / SAMPLES * 100).toFixed(2) + "%"
return `${this.p} / ${this.target} [${progressBar}] (${percent})`
} else {
return `Done! (${this.target} samples)`
}
},
progress() { this.p++ }
}
Object.defineProperty(window, "progress", { configurable: true, get: () => progressObj.toString() })
const nextFrame = () => new Promise(requestAnimationFrame)
let hist = new Map()
let t = await nextFrame()
for (let i = 0; i < SAMPLES; i++) {
progressObj.progress()
let nt = await nextFrame()
let d = nt - t
hist.set(d, (hist.get(d) || 0) + 1)
t = nt
}
const compareOn = f => (a, b) => f(a) - f(b)
const onProp = p => compareOn(x => x[p])
console.table(
Array.from(hist, ([delta, count]) => ({delta, count}))
.sort(onProp `delta`)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment