timedLoop()

Category:Control

Executes the callback function code every time a certain number of milliseconds has elapsed, until stopped using stopTimedLoop().

Some apps need to repeat code using a timed delay, 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 repetition of the loop to start. You can either let the callback function keep running indefinitely until the app is stopped, or use the stopTimedLoop() command to stop all running timed loops. For more advance usage, you can assign the return value of timedLoop() to a variable, which you can then pass to stopTimedLoop() in order to stop only a specific timed loop, ignoring the rest.

Examples

Seconds Elapsed

Count the number of seconds elapsed since the program started running.

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

Ten Timed Moves

Make 10 random turtle moves in half second intervals.

// Make 10 random turtle moves in half second intervals. 
var count=0;
timedLoop(500, 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) {
  	stopTimedLoop();
  }
});

Syntax

timedLoop(ms, callback)

Parameters

Name Type Required? Description
callback Function A function to execute each time the loop is repeated.
ms Number The number of milliseconds to wait before each repetition of the loop.

Returns

Returns a timed loop object which can be passed to stopTimedLoop() to stop only a specific loop.

Tips

  • Use the stopTimedLoop() function to end the timed loop.
  • Do not put functions inside a loop that contain timers, like further calls to timedLoop(). The loop will not wait for the timer to complete.
  • timedLoop() is built on top of the core JavaScript function setInterval()

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