setTimeout

Category:Control

setTimeout(callback, ms)

Category: Control

Sets a timer and executes code when that number of milliseconds has elapsed.

Some apps need code to be executed once after a certain amount of time has elapsed, like a bank logon is disabled if you take to long to enter your password. Other code in your app can be executed while waiting for the timeout interval to end. setTimeout() returns a numeric value that can be used with clearTimeout(timeout) to prevent the execution of the callback function.

Examples


setTimeout(function() {
  console.log("1000 milliseconds have elapsed");
}, 1000);

Example: Pause between Moves Use the timeout function to make the turtle pause between two moves.

// Use the timeout function to make the turtle pause between two moves.
moveForward(50);
setTimeout(function() {
  moveForward(100);
}, 2000);

Example: Pause between Moves v2 Use the timeout function to make the turtle pause between two moves. Note how the turnRight() does not wait for the timeout.

// Use the timeout function to make the turtle pause between two moves. Note how the turnRight() does not wait for the timeout.
moveForward(50);
setTimeout(function() {
  moveForward(100);
}, 2000);
turnRight(90);

Example: Click Speed Count the number of clicks of a button in 10 seconds.

//  Count the number of clicks of a button in 10 seconds.
textLabel("instructions", "Click the button as many times as possible in 10 seconds");
button("gameButton", "Click me!");
textLabel("results", "");
var counter = 0;
setTimeout(function() {
  hideElement("gameButton");
  console.log("10000 milliseconds have elapsed");
}, 10000);
onEvent("gameButton", "click", function(){
  counter = counter + 1;
  setText("results", "You have clicked " + counter + " times.");
});

Syntax

setTimeout(callback, ms);

Parameters

Name Type Required? Description
callback function Yes A function to execute when the timeout interval has completed.
ms number Yes The number of milliseconds to wait before executing the function.

Returns

A numeric interval timer ID, which can be used to cancel the timer before it executes.

Tips

  • Use the clearTimeout(timeout) function to cancel the execution of code scheduled using setTimeout().
  • Do not put functions inside a loop that contain timers, like setTimeout(). 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