Skip to content

Commit

Permalink
🧪 add fps counter to playground
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Feb 12, 2024
1 parent 5fee9f8 commit fb03a1a
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<button id="queue-task">waitNextTask()</button>
<button id="simulate-work">simulateWork()</button>
<button id="post-task-vs-yield-or-continue">postTask() vs yieldOrContinue()</button>
<code class="fps"></code>
</div>
<div>
<span id="animation">animation</span>
Expand Down
7 changes: 7 additions & 0 deletions playground/playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { isTimeToYield, SchedulingStrategy, yieldOrContinue } from '../index'
import simulateWork from './utils/simulateWork'
import waitNextTask from '../src/utils/waitNextTask'
import withResolvers from '../src/utils/withResolvers'
import fps from './utils/fps'

document.querySelector('#run-interactive')!.addEventListener('click', () => {
run('interactive')
Expand Down Expand Up @@ -44,6 +45,12 @@ document.querySelector('#queue-task')!.addEventListener('click', () => {
runWaitNextTask()
})

setInterval(() => {
document.querySelector(
'.fps',
)!.textContent = `frameRate: ${fps.guessRefreshRate()}, fps: ${fps.fps()}`
}, 20)

async function run(strategy: SchedulingStrategy, time: number = 1000) {
const start = performance.now()
while (performance.now() - start < time) {
Expand Down
44 changes: 44 additions & 0 deletions playground/utils/fps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class FPS {
#fps = 0
#frames: number[] = []

constructor() {
this.#loop()
}

fps(): number {
if (this.#fps === 61) {
return 60
}
return this.#fps
}

guessRefreshRate(): 60 | 120 {
return this.#fps >= 70 ? 120 : 60
}

#loop(): void {
requestAnimationFrame(() => {
this.#loop()
this.#frames.push(performance.now())

this.#updateFps()
})
}

#updateFps(): void {
while (true) {
const oldestFrame = this.#frames.at(0)
if (oldestFrame !== undefined && oldestFrame < performance.now() - 1000) {
this.#frames.shift()
} else {
break
}
}
this.#fps = this.#frames.length
}
}

const fps = new FPS()

export default fps

0 comments on commit fb03a1a

Please sign in to comment.