Lesson 28 - JavaScript setTimeout and setInterval
JavaScript provides setTimeout
and setInterval
for handling delayed and repeated execution of functions. We have already encountered them in our previous lessons, let's explore them now in detail.
Explanation
setTimeout(function, delay)
: Executes a function once after a specified delay (in milliseconds).setInterval(function, delay)
: Repeats execution of a function every specified milliseconds until stopped.- Use
clearTimeout()
andclearInterval()
to cancel them.
Example 1: setTimeout
(Delayed Execution)
console.log("Hello! Wait for 3 seconds...");
setTimeout(() => {
console.log("3 seconds later...");
}, 3000);
- Prints
"Hello!"
immediately, then"3 seconds later..."
after 3 seconds.
Example 2: setInterval
(Repeated Execution)
let counter = 1;
let intervalId = setInterval(() => {
console.log(`Counter: ${counter}`);
counter++;
if (counter > 5) clearInterval(intervalId); // Stops after 5 executions
}, 1000);
- Logs
Counter: 1
,Counter: 2
... up toCounter: 5
at 1-second intervals.
Example 3: Stopping setTimeout
let timeoutId = setTimeout(() => {
console.log("This will not print.");
}, 5000);
clearTimeout(timeoutId); // Cancels the timeout
- The function is never executed because
clearTimeout()
was called.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson28-timers.html
.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 28 - Timers</title> </head> <body> <script> console.log("Hello! Wait for 3 seconds..."); setTimeout(() => { console.log("3 seconds later..."); }, 3000); let counter = 1; let intervalId = setInterval(() => { console.log(`Counter: ${counter}`); counter++; if (counter > 5) clearInterval(intervalId); }, 1000); </script> </body> </html>
-
-
Save the File.
-
Open Developer Console (
F12
) to See the Logs.
Experiment
- Change
setTimeout
to 5 seconds. - Modify
setInterval
to stop after 10 counts instead of 5. - Use
clearInterval()
inside an event listener (e.g., button click) to stop the interval.
Key Takeaways
setTimeout
runs a function once after a delay.setInterval
repeats execution at set intervals.clearTimeout
andclearInterval
cancel scheduled executions.