Skip to content

Instantly share code, notes, and snippets.

@simonghales
Last active March 23, 2024 23:26
Show Gist options
  • Save simonghales/3bf189c97f0a0fea2f028566c45ce414 to your computer and use it in GitHub Desktop.
Save simonghales/3bf189c97f0a0fea2f028566c45ce414 to your computer and use it in GitHub Desktop.
Running a game loop on a web worker
export const createNewPhysicsLoopWebWorker = (stepRate: number) => {
return new Worker('data:application/javascript,' +
encodeURIComponent(`
var start = performance.now();
var updateRate = ${stepRate};
function getNow() {
return start + performance.now();
}
var lastUpdate = -1;
var accumulator = 0;
function step() {
if (lastUpdate < 0) {
lastUpdate = getNow() - updateRate;
}
var now = getNow();
var delta = now - lastUpdate;
lastUpdate = now;
accumulator += delta;
if (accumulator > updateRate) {
accumulator = 0;
self.postMessage('step');
} else {
var difference = updateRate - accumulator;
if (difference < 3) {
var start = getNow();
var endTime = start + difference;
var now = getNow();
while (now < endTime) {
now = getNow();
}
accumulator = 0;
self.postMessage('step');
}
}
setTimeout(step, updateRate - 2);
}
step()
`) );
}
const worker = new Worker('data:application/javascript,' +
encodeURIComponent(`
var start = performance.now();
var updateRate = ${stepRate};
function getNow() {
return start + performance.now();
}
var lastUpdate = getNow();
var accumulator = 0;
while(true) {
var now = getNow();
var delta = now - lastUpdate;
lastUpdate = now;
accumulator += delta;
if (accumulator > updateRate) {
accumulator -= updateRate;
self.postMessage('step')
}
}
`) );
worker.onmessage = (event) => {
if (event.data === 'step') {
stepWorld()
}
}
@simonghales
Copy link
Author

Because setTimeout defaults to a minimum of 4ms delay, methods such as the ones used here don't quite work, as the 4ms delay is typically enough for your updates to fall out of rhythm.

The solution? Create a dedicated web worker that is dedicated solely for determining when your game should update. In this case you can use the while true loop approach without blocking any other code from executing. As far as I can tell so far, it's working pretty flawlessly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment