Lets say our code simulates physics of 100k particles and looks like this:
function simulateOneStep() {
for(const particle in this.particles) {
// do math and mutate particle
particle.x += ...
particle.y += ...
}
}
Explore the easiest way to make this async such that it adapts to perf:
function* asyncSimulator() {
while(true) {
for(const particle in this.particles) {
...
yield;
}
}
}
const simulator = asyncSimulator();
function animate() {
const curTime = Date.now();
while(Date.now() - curTime < 16) { // do 16ms work
simulator.next();
}
}