JavaScript Timeouts
setTimeout runs a function once after a delay. The delay is counted in milliseconds, so 1000 means one second.
The timer runs last
The timer is set for 50 milliseconds. Both plain lines run first, and the timer line arrives after them.
console.log("Start");
setTimeout(function () {
console.log("Timer done");
}, 50);
console.log("End");A timer changes the page
The waiting line prints at once. The timer then writes into the paragraph and logs the read-back.
const demo = document.getElementById("demo");
console.log("Waiting");
setTimeout(function () {
demo.textContent = "Time is up";
console.log(demo.textContent);
}, 50);Shorter delay, earlier run
Two timers are waiting at once. The one with the shorter delay runs first.
setTimeout(function () {
console.log("Later");
}, 80);
setTimeout(function () {
console.log("Sooner");
}, 30);Example
const demo = document.getElementById("demo");
console.log("Start");
setTimeout(function () {
demo.textContent = "Timer changed this text";
console.log(demo.textContent);
}, 50);
console.log("End");Key points
- setTimeout takes a function and a delay in milliseconds.
- Timers wait, and the rest of the script does not.
- Lines after the setTimeout call run before the timer function.
- setInterval runs a function again and again on a repeating delay.
- clearTimeout cancels a timer that has not run yet.
In this example, the Start and End lines print while the timer is still waiting. After 50 milliseconds the timer function runs and changes the paragraph text. Its log line reads the new text back.
Note
a delay is a minimum wait, not an exact appointment.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
In a script that logs Start, sets a 50 ms timer, then logs End, which line prints last?