JavaScript Timing Events – setTimeout, setInterval, clearTimeout, clearInterval
14 April 2025 | Category: JavaScript
JavaScript provides timing functions that let you execute code after a delay or repeatedly at intervals.
📌 1. setTimeout()
– Run Once After Delay
setTimeout()
runs a function once after a specified delay (in milliseconds).
✅ Syntax:
setTimeout(function, delay);
✅ Example:
setTimeout(() => {
console.log("This runs after 3 seconds");
}, 3000);
✅ Use Case:
<button onclick="delayedMessage()">Click Me</button>
<script>
function delayedMessage() {
setTimeout(() => {
alert("This message appeared after 2 seconds!");
}, 2000);
}
</script>
📌 2. setInterval()
– Run Repeatedly
setInterval()
runs a function repeatedly at specified time intervals.
✅ Syntax:
setInterval(function, interval);
✅ Example:
setInterval(() => {
console.log("This runs every 1 second");
}, 1000);
✅ Use Case:
<button onclick="startTimer()">Start Counter</button>
<p id="counter">0</p>
<script>
let count = 0;
let timer;
function startTimer() {
timer = setInterval(() => {
count++;
document.getElementById("counter").innerText = count;
}, 1000);
}
</script>
❌ Stop Timers
✅ clearTimeout()
– Stop setTimeout
You need to store the timer in a variable and cancel it if needed.
let timeoutId = setTimeout(myFunction, 5000);
clearTimeout(timeoutId); // Cancels the timeout
✅ clearInterval()
– Stop setInterval
let intervalId = setInterval(myFunction, 1000);
clearInterval(intervalId); // Stops repeating
✅ Example with Stop Button
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<p id="time">0</p>
<script>
let time = 0;
let interval;
function start() {
interval = setInterval(() => {
time++;
document.getElementById("time").innerText = time;
}, 1000);
}
function stop() {
clearInterval(interval);
}
</script>
⏳ Difference Between setTimeout
& setInterval
Function | Runs Once | Repeats | Can be Stopped |
---|---|---|---|
setTimeout | ✅ | ❌ | Yes with clearTimeout() |
setInterval | ❌ | ✅ | Yes with clearInterval() |
🧠 Tip: Use setTimeout
for Delayed Animations
setTimeout(() => {
document.body.style.backgroundColor = "skyblue";
}, 2000);
✅ Summary
Function | Use Case |
---|---|
setTimeout() | Delay a task |
setInterval() | Repeat a task periodically |
clearTimeout() | Cancel delayed execution |
clearInterval() | Stop repeated execution |