The “game loop” is a name given to a technique used to render animations and games with changing state over time. At its heart is a function that runs as many times as possible, taking user input, updating the state for the elapsed time, and then drawing the frame.
Here’s what game loop in JavaScript looks like:
function update(progress) {
// Update the state of the world for the elapsed time since last render
}
function draw() {
// Draw the state of the world
}
function loop(timestamp) {
var progress = timestamp - lastRender
update(progress)
draw()
lastRender = timestamp
window.requestAnimationFrame(loop)
}
var lastRender = 0
window.requestAnimationFrame(loop)
Our first animation will be super simple. A red square that moves to the right until it reaches the edge of the canvas and loops back around to the start.
We’ll need to store the square’s position and increment the x position in our update function. When we hit a boundary we can subtract the canvas width to loop back around.
var width = 800
var height = 200
var state = {
x: width / 2,
y: height / 2
}
function update(progress) {
state.x += progress
if (state.x > width) {
state.x -= width
}
}