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.
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."); });
setTimeout(callback, ms);
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. |
A numeric interval timer ID, which can be used to cancel the timer before it executes.
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