setInterval

Category:Control

setInterval(callback, ms)

Category: Control

Executes the callback function code every time a certain number of milliseconds has elapsed, until cleared.

Some apps need to execute code at a set interval, like the mole appearing every 5 seconds or so in "Whack a Mole". Other code in your app can be executed while waiting for the next interval to end. You can either let the callback function keep running on its interval until the app is stopped, or use the interval ID value returned by setInterval() to stop the interval timer with a call to clearInterval(interval).

Examples


var seconds = 0;
setInterval(function() {
  seconds = seconds + 1;
  console.log(seconds + " seconds have elapsed");
}, 1000);

Example: Ten Timed Moves Make 10 random turtle moves in half second intervals.

// Make 10 random turtle moves in half second intervals. 
var count=0;
var intervalID = setInterval(function(){
  var x = randomNumber(-50, 50);
  var y = randomNumber(-50, 50);
  console.log("Move " + x + " horizontally and " + y + " vertically.");
  move(x, y);
  count=count+1;
  if (count==10) clearInterval(intervalID);
}, 500);

Example: Blinker Use the interval and timeout functions to make a text label blink, one second on and one second off.

// Use the interval and timeout functions to make a text label blink, one second on and one second off.
textLabel("blinker", "This text blinks");
setInterval(function() {
  showElement("blinker");
  setTimeout(function() {
    hideElement("blinker");
  }, 1000);
}, 2000);

Syntax

setInterval(callback, ms);

Parameters

Name Type Required? Description
callback function Yes A function to execute at the interval designated.
ms number Yes The number of milliseconds between each execution of the function.

Returns

A numeric interval timer ID, which can be used to cancel it when it is no longer needed.

Tips

  • Use the clearInterval(interval) function to stop the interval timer.
  • Do not put functions inside a loop that contain timers, like setInterval(). The loop will not wait for the timer to complete.

Found a bug in the documentation? Let us know at documentation@code.org

Found a bug in the documentation? Let us know at documentation@code.org