setTimeout
Learn to run code once after a delay with setTimeout.
Delayed call with setTimeout
setTimeout runs a function once after a delay. The delay is in milliseconds: 1000 ms = 1 second. The callback is usually written as an arrow function.
setTimeout(() => {
console.log('Hello');
}, 1000);This code logs Hello after 1 second. The callback runs only once. The page does not freeze while the timer waits; other code keeps running right away.
Passing extra arguments to setTimeout
You can pass extra parameters to setTimeout after the callback. These parameters are passed as arguments when the callback is called.
function greet(name) {
console.log('Hello ' + name);
}
setTimeout(greet, 1000, 'Alex');This code logs Hello Alex after 1 second. The third parameter 'Alex' is passed to the callback as the name argument. You can add more arguments with commas.
Exercise Change button text after 1 second
Select a button and use setTimeout to change its text to 'Done' after 1 second. Use button.textContent.
Show example solution
const button = document.querySelector('button');
setTimeout(() => {
button.textContent = 'Done';
}, 1000);
Test yourself
-
What is the delay in the code below?
setTimeout(() => { console.log('Hello'); }, 2500);- 2.5 hours
- 2500 milliseconds
- 2500 seconds
- 2500 minutes
Show answer
2500 milliseconds — Correct! 2500 is in milliseconds, which is 2.5 seconds.
-
Complete the setTimeout call
setTimeout(() => { console.log('Ready'); }, ____);Show answer
setTimeout(() => { console.log('Ready'); }, 1000); -
Match the setTimeout parts
- setTimeout
- starts a timer
- callback
- runs after the delay
- 1000
- equals 1 second
- return value
- is the timer id