The Official Description

Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.


Using setInterval()

A major use for setInterval() is in animation. In animation you need to display a frame of the scene every few milliseconds (what is frame rate?) in order to fool the eye into thinking the animation is continuous.

setInterval() allows you to do this. It will execute the code you choose at a specified interval. If you want to run your animation at 25 FPS (Frames Per Second) then you would call setInterval passing in 4 as the second parameter. This will call your code ever 4 milliseconds or 25 times in one second.

The example below calls a function every 10 milliseconds creating the illusion of a square moving across the canvs.

Editor (write code below)
var canvas = document.getElementById('set_interval_interactive1'); var context = canvas.getContext('2d'); var direction = 'right'; var size = 30; var x = 0; var y = 150; var interval; function drawSquare() { context.fillRect(x, y, size, size); } function adjustPosition() { if (direction == 'right') { x += 1; if (x + size >= canvas.width) { direction = 'left'; } } else { x -= 1; if (x <= 0) { direction = 'right'; } } } function runProgram() { context.clearRect(0, 0, canvas.width, canvas.height); adjustPosition(); drawSquare(); } function playGame() { interval = setInterval(runProgram, 10); } function pauseGame() { clearInterval(interval); context.font = "20px serif"; context.textAlign = 'center'; context.fillText('Click anywhere on the canvas to restart animation.', canvas.width / 2, 50); } canvas.addEventListener('focus', playGame); canvas.addEventListener('blur', pauseGame);
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run and Focus Canvas
Canvas (your drawing will display here)

Ready for the next lesson?

Next up, the "Event Listeners" lesson >