Introductions
JavaScript timing functions allow you to run code after a certain amount of time or repeatedly at fixed intervals. The two most important functions are setTimeout() and setInterval(). You can use them to create countdowns, digital clocks, delayed messages, automatic counters, animations, and many other interactive features. JavaScript setTimeout() and setInterval() practice questions with solutions help to understand the concepts.
Question 1: Run Code After a Delay
Problem
Display a message after 3 seconds using setTimeout().
Solution
setTimeout(function() {
console.log("Hello! 3 seconds have passed.");
}, 3000);
Output
Immediately:
Nothing appears
After 3 seconds:
Hello! 3 seconds have passed.
Step-by-step Explanation
setTimeout()schedules a function.- The first argument is the function to execute.
3000means 3000 milliseconds.- 1000 milliseconds equals 1 second.
- Therefore, 3000 milliseconds equals 3 seconds.
- The function runs once after approximately 3 seconds.
Question 2: Display a Delayed Message on a Webpage
Problem
Create a button. When the user clicks it, display a message after 2 seconds.
Solution
<button id="button">Click Me</button>
<p id="message"></p>
<script>
const button = document.getElementById("button");
const message = document.getElementById("message");
button.addEventListener("click", function() {
message.textContent = "Please wait...";
setTimeout(function() {
message.textContent = "Your message is ready!";
}, 2000);
});
</script>
Output
Immediately after clicking:
Please wait...
After 2 seconds:
Your message is ready!
Step-by-step Explanation
- The button listens for a click.
- The first message appears immediately.
setTimeout()starts a 2-second timer.- After 2 seconds, the second message replaces the first one.
- The function runs only once.
Question 3: Use setTimeout() with an Arrow Function
Problem
Use an arrow function with setTimeout() to display a message after 5 seconds.
Solution
setTimeout(() => {
console.log("The timer has finished.");
}, 5000);
Output
After 5 seconds:
The timer has finished.
Step-by-step Explanation
The traditional syntax is:
setTimeout(function() {
console.log("Done");
}, 5000);
The arrow function version is shorter:
setTimeout(() => {
console.log("Done");
}, 5000);
Both perform the same basic task.
Question 4: Create a Counter with setInterval()
Problem
Create a counter that increases by 1 every second.
Solution
<p id="counter">0</p>
<script>
const counter = document.getElementById("counter");
let number = 0;
setInterval(function() {
number++;
counter.textContent = number;
}, 1000);
</script>
Output
The value changes every second:
0
1
2
3
4
5
...
Step-by-step Explanation
numberstarts at0.setInterval()runs the function repeatedly.1000means one second.- Every second,
numberincreases by 1. - The new value is displayed.
- Unlike
setTimeout(),setInterval()keeps repeating until stopped.
Question 5: Stop an Interval Using clearInterval()
Problem
Create a counter that increases every second and stops when the user clicks a button.
Solution
<p id="counter">0</p>
<button id="stopButton">Stop Counter</button>
<script>
const counter = document.getElementById("counter");
const stopButton = document.getElementById("stopButton");
let number = 0;
const timer = setInterval(function() {
number++;
counter.textContent = number;
}, 1000);
stopButton.addEventListener("click", function() {
clearInterval(timer);
});
</script>
Output
The counter starts:
1
2
3
4
5
After clicking Stop Counter:
5
The counter stops increasing.
Step-by-step Explanation
setInterval()returns an interval ID.- That ID is stored in
timer. - The counter increases every second.
clearInterval(timer)stops the interval.- After stopping, the function no longer runs.
Question 6: Cancel a setTimeout()
Problem
Create a delayed message and a Cancel button. If the user clicks Cancel before the timer finishes, prevent the message from appearing.
Solution
<button id="startButton">Start</button>
<button id="cancelButton">Cancel</button>
<p id="message"></p>
<script>
const startButton = document.getElementById("startButton");
const cancelButton = document.getElementById("cancelButton");
const message = document.getElementById("message");
let timer;
startButton.addEventListener("click", function() {
message.textContent = "Message scheduled...";
timer = setTimeout(function() {
message.textContent = "Time is up!";
}, 5000);
});
cancelButton.addEventListener("click", function() {
clearTimeout(timer);
message.textContent = "Timer cancelled.";
});
</script>
Output
After clicking Start:
Message scheduled...
If Cancel is clicked before 5 seconds:
Timer cancelled.
If Cancel is not clicked:
Time is up!
Step-by-step Explanation
setTimeout()returns a timer ID.- The ID is stored in
timer. clearTimeout(timer)cancels the scheduled function.- The message therefore never reaches the
"Time is up!"state when cancelled.
Question 7: Create a Countdown Timer
Problem
Create a countdown that starts from 10 and decreases by 1 every second until it reaches 0.
Solution
<h2 id="countdown">10</h2>
<script>
const countdown = document.getElementById("countdown");
let number = 10;
const timer = setInterval(function() {
number--;
countdown.textContent = number;
if (number === 0) {
clearInterval(timer);
countdown.textContent = "Time's up!";
}
}, 1000);
</script>
Output
The countdown appears like:
10
9
8
7
6
5
4
3
2
1
Time's up!
Step-by-step Explanation
- The counter starts at
10. setInterval()runs every second.number--decreases the value by 1.- The updated number is displayed.
- When the value reaches
0,clearInterval()stops the timer. - The final message is displayed.
Question 8: Create a Digital Clock
Problem
Create a digital clock that displays the current hours, minutes, and seconds and updates every second.
Solution
<h2 id="clock"></h2>
<script>
const clock = document.getElementById("clock");
function updateClock() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const seconds = String(now.getSeconds()).padStart(2, "0");
clock.textContent =
hours + ":" + minutes + ":" + seconds;
}
updateClock();
setInterval(updateClock, 1000);
</script>
Output
The clock may display:
14:32:08
One second later:
14:32:09
Step-by-step Explanation
new Date()gets the current date and time.getHours()gets the current hour.getMinutes()gets the current minutes.getSeconds()gets the current seconds.padStart()ensures single-digit values display with a leading zero.updateClock()updates the page.setInterval()runs the function every second.
Question 9: Change a Message Automatically
Problem
Display different messages every 2 seconds.
Solution
<p id="message">Loading...</p>
<script>
const message = document.getElementById("message");
const messages = [
"Welcome to JavaScript!",
"Keep practicing!",
"You are doing great!",
"Keep learning!"
];
let index = 0;
const timer = setInterval(function() {
message.textContent = messages[index];
index++;
if (index === messages.length) {
clearInterval(timer);
}
}, 2000);
</script>
Output
The messages appear one after another:
Welcome to JavaScript!
After 2 seconds:
Keep practicing!
After another 2 seconds:
You are doing great!
Then:
Keep learning!
The interval stops after the final message.
Step-by-step Explanation
- An array stores the messages.
indexstarts at0.- Every 2 seconds, one message is displayed.
index++moves to the next message.- When all messages have been displayed,
clearInterval()stops the timer.
Question 10: Build a Start, Pause, and Reset Stopwatch
Problem
Build a simple stopwatch with:
- Start button
- Pause button
- Reset button
The stopwatch should count seconds.
Solution
<h2 id="time">0</h2>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
<script>
const time = document.getElementById("time");
const startButton = document.getElementById("start");
const pauseButton = document.getElementById("pause");
const resetButton = document.getElementById("reset");
let seconds = 0;
let timer = null;
startButton.addEventListener("click", function() {
if (timer !== null) {
return;
}
timer = setInterval(function() {
seconds++;
time.textContent = seconds;
}, 1000);
});
pauseButton.addEventListener("click", function() {
clearInterval(timer);
timer = null;
});
resetButton.addEventListener("click", function() {
clearInterval(timer);
timer = null;
seconds = 0;
time.textContent = seconds;
});
</script>
Output
Initial state:
0
[Start] [Pause] [Reset]
After clicking Start:
1
2
3
4
5
After clicking Pause:
5
The counter stops.
After clicking Reset:
0
Step-by-step Explanation
secondsstores the stopwatch value.timerstores the interval ID.- Start creates an interval.
- Every second,
secondsincreases. - The value is displayed on the page.
clearInterval()stops the timer when Pause is clicked.- Setting
timer = nullallows the stopwatch to be started again. - Reset stops the timer.
- Reset sets
secondsback to0. - The displayed value is updated.
Key Takeaways
setTimeout()runs code once after a delay.setInterval()runs code repeatedly at a fixed interval.1000milliseconds equals 1 second.clearTimeout()cancels a scheduledsetTimeout().clearInterval()stops a runningsetInterval().setTimeout()returns a timer ID.setInterval()also returns an interval ID.- Store timer IDs when you may need to cancel them later.
- Timers are useful for countdowns, clocks, delays, notifications, and games.
setInterval()should be stopped when it is no longer needed.- JavaScript timers do not guarantee that code will execute at exactly the specified millisecond; they schedule the callback to run after the delay when the browser’s event loop can process it.
FAQs
1. What is setTimeout() in JavaScript?
setTimeout() runs a function once after a specified delay.
setTimeout(function() {
console.log("Hello");
}, 2000);
The function runs after approximately 2 seconds.
2. What is setInterval() in JavaScript?
setInterval() repeatedly runs a function after a specified time interval.
setInterval(function() {
console.log("Hello");
}, 1000);
The message is logged approximately every second until the interval is stopped.
3. What is the difference between setTimeout() and setInterval()?
The main difference is repetition.
setTimeout():
Runs once
setInterval():
Runs repeatedly
For example, use setTimeout() for a delayed notification and setInterval() for a clock.
4. How do I stop setInterval()?
Use clearInterval().
const timer = setInterval(function() {
console.log("Running");
}, 1000);
clearInterval(timer);
You need the interval ID to stop it.
5. How do I cancel setTimeout()?
Use clearTimeout().
const timer = setTimeout(function() {
console.log("Hello");
}, 5000);
clearTimeout(timer);
If the timeout has not executed yet, it will be cancelled.
6. What does 1000 mean in setTimeout()?
The timing value is measured in milliseconds.
1000 ms = 1 second
2000 ms = 2 seconds
5000 ms = 5 seconds
For example:
setTimeout(function() {
console.log("Done");
}, 3000);
The callback is scheduled after approximately 3 seconds.
7. Can setInterval() be used to create a countdown?
Yes. A common approach is to decrease a number every second.
let number = 10;
const timer = setInterval(function() {
number--;
console.log(number);
if (number === 0) {
clearInterval(timer);
}
}, 1000);
This creates a simple countdown.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
