Skip to content

Commit

Permalink
Improve frame rate consistency in emulator loop
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscodelahoz committed Apr 18, 2024
1 parent 7ddcc8d commit 8adfaf0
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/scripts/emulator/emulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,24 @@ export class Chip8Emulator {
private startEmulatorLoop() {
const frameTime = 1000 / 60;

const previousTime = Date.now();
let nextFrameMidpoint = previousTime + frameTime / 2;

this.emulationLoop = window.setInterval(() => {
try {
this.cpuInstance.cycle();
} catch(error) {
this.stopEmulatorLoop();
console.error((error as Error).message);
const currentTime = Date.now();
let cycleCount = 0;

// Run the emulator cycle up to twice per interval to catch up on missed frames
while (nextFrameMidpoint < currentTime - frameTime && cycleCount < 2) {
try {
this.cpuInstance.cycle();
} catch(error) {
this.stopEmulatorLoop();
console.error((error as Error).message);
}

nextFrameMidpoint += frameTime;
cycleCount++;
}
}, frameTime);
}
Expand Down

0 comments on commit 8adfaf0

Please sign in to comment.