- Automatically when the page loads
- When your script calls a function
- In response to some event, such as the user clicking a button
- Have some code run once after a specified number of milliseconds. This is called a timeout.
- Have some code run after a specified number of milliseconds, and then repeat each time that number of milliseconds expires. This is called an interval.
Using a timeout to perform a future action once
To set up a JavaScript timeout, use thewindow
object’s setTimeout()
method:
setTimeout(<em>function</em>, <em>delay</em>, <em>arg1</em>, <em>arg2</em>, …)
function
: The name of a function that you want JavaScript to run when the timeout expires. Instead of a function, you can also use a JavaScript statement, surrounded by quotation marks.delay
: The number of milliseconds that JavaScript waits before executingfunction
.arg1
,arg2
, …: Optional arguments to pass tofunction
.
setTimeout()
returns a value that uniquely identifies the timeout. You can store this value just in case you want to cancel the timeout.Here's some code that shows how setTimeout()
works:
// Create a message var str = "Hello World!";The script begins by creating a message string and storing it in the// Set the timeout var timeoutId = setTimeout(logIt, 2000, str);
// Run this function when the timeout occurs function logIt(msg) { // Display the message console.log(msg); }
str
variable. Then the setTimeout()
method runs:
setTimeout(logIt, 2000, str);This tells JavaScript to run the function named
logIt()
after two seconds (2,000 milliseconds) have elapsed, and to pass the str
variable to that function. The logIt()
function takes the msg
argument and displays it in the console.If you've set up a timeout and then decide that you don’t want the code to execute after all for some reason, you can cancel the timeout by running the clearTimeout()
method:
clearTimeout(<em>id</em>);
id
: The name of the variable that was used to store thesetTimeout()
method's return value
var timeoutId = setTimeout(logIt, 2000, str);Then you’d cancel the timeout using the following statement:
clearTimeout(timeoutId);
Using an interval to perform a future action repeatedly
Running code once after a specified number of seconds is only an occasionally useful procedure. A much more practical skill is being able to repeat code at a specified interval. This enables you to set up countdowns, timers, animations, image slide shows, and more. To set up an interval, use the window object’ssetInterval()
method:
setInterval(<em>function</em>, <em>delay</em>, <em>arg1</em>, <em>arg2</em>, …)
function
: The name of a function that you want JavaScript to run at the end of each interval. Instead of a function, you can also use a JavaScript statement, surrounded by quotation marks.delay
: The number of milliseconds in each interval, after which JavaScript executesfunction
arg1
,arg2
, …: Optional arguments to pass tofunction
setTimeout()
, the setInterval()
method returns a value that uniquely identifies the interval. You use that value to cancel the interval with the clearInterval()
method:
clearInterval(<em>id</em>);
id
: The name of the variable that was used to store the setInterval() method's return value
var intervalId = setInterval(countdown, 5000);Then you’d cancel the interval using the following statement:
clearInterval(intervalId);Note that although the
clearTimeout()
method is optional with setTimeout()
, you should always use clearInterval()
with setInterval()
. Otherwise, the interval will just keep executing.The following code demonstrates both setInterval()
and clearInterval()
.
var counter = 10;The purpose of this script is to display a countdown from 10 to 0 in the console. The script begins by declaring a variable named// Set the interval var intervalId = setInterval(countdown, 1000);
// Run this function at the end of each interval function countdown() {
// Display the countdown and then decrement the counter console.log(counter--); // Cancel the interval when we hit 0 if (counter < 0) { clearInterval(intervalId); console.log("All done!"); } }
counter
and initializing it to 10
. Then the setInterval()
method sets up a function named countdown()
to run at intervals of one second (1,000 milliseconds). The countdown()
function displays the current value of counter
in the console and then decrements counter
. Then an if()
test checks the value of counter
. If it's negative, it means that counter
was just 0
, so it's done. The clearInterval()
method cancels the interval, and then a final console message is logged.