Game Loop
<canvas id="game" width="320" height="180"></canvas>
<script>
const canvas = document.querySelector("#game");
const ctx = canvas.getContext("2d");
const step = 1 / 60;
let acc = 0;
let last = performance.now();
const player = { x: 20, y: 80, speed: 80 };
function update(dt) {
player.x += player.speed * dt;
if (player.x > 300) player.x = 20;
}
function draw() {
ctx.fillStyle = "#1b2430";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#8bd3dd";
ctx.fillRect(player.x, player.y, 16, 16);
}
function frame(now) {
requestAnimationFrame(frame);
let elapsed = (now - last) / 1000;
last = now;
if (elapsed > 0.1) elapsed = 0.1;
acc += elapsed;
let steps = 0;
while (acc >= step && steps < 5) {
update(step);
acc -= step;
steps += 1;
}
draw();
}
requestAnimationFrame(frame);
</script>