JavaScript timers are methods that allow you to execute a piece of code at a specific time or at repeated intervals. They are a fundamental part of asynchronous JavaScript, enabling tasks to be scheduled without blocking the main thread.
2. setTimeout
The setTimeout() method executes a function or a specified piece of code once after a specified delay (in milliseconds).
document.write("Start");
setTimeout(() => {
document.write("Executed after 2 seconds");
}, 2000); // 2000 ms = 2 seconds
document.write("End"); // This logs before the timeout
3. setInterval
The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
let intervalId = setInterval(() => {
document.write("Executed every 1 second");
}, 1000);
// Stop interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
document.write("Interval stopped.");
}, 5000);
4. Example: Timer Demo
This example demonstrates a simple counter using setInterval and clearInterval.
0
5. Comparison Table: setTimeout vs setInterval
Function
Purpose
Stop Method
Use Case
setTimeout
Executes a function once after a delay.
clearTimeout
Showing a popup after 5 seconds.
setInterval
Executes a function repeatedly at a set interval.
clearInterval
Updating a clock every second.
✅ Best Practice: Always assign the result of setInterval or setTimeout to a variable so you can clear it later using clearInterval() or clearTimeout() to prevent memory leaks.
Practice Questions
Test your understanding of JavaScript Timers.
Easy
Q1: Create a basic timeout.
Write a setTimeout function.
Pass a callback function that logs "Hello World!" to the console.
Set the delay to 3 seconds (3000 milliseconds).
Use setTimeout() and pass a callback function along with the time in milliseconds (3 seconds = 3000ms).