Assignments Of Day 23:
JavaScript Timing Events
Below are some assignments based
on the JavaScript timing events concept (setTimeout(), setInterval(),
clearTimeout(), clearInterval()), along with step-by-step solutions and
explanations:
Assignment
1: Delayed Message Using setTimeout()
Problem:
Write a JavaScript program that displays a message to the user after a delay of
3 seconds. The message should say: "Hello! You will see this message after
3 seconds."
Solution:
javascript
Copy code
// Step
1: Set a timeout using setTimeout
setTimeout(function()
{
// Step 2: Display the message after 3
seconds
alert("Hello! You will see this message
after 3 seconds.");
}, 3000);
// 3000 milliseconds = 3 seconds
Explanation:
- setTimeout() is
used to execute a function after a delay of 3000 milliseconds (3 seconds).
- The
anonymous function inside setTimeout() will display an alert with the
message after the delay.
Assignment
2: Countdown Timer Using setInterval()
Problem:
Create a countdown timer that starts from 10 seconds and counts down to 0,
updating every second. Once it reaches 0, stop the countdown.
Solution:
javascript
Copy code
// Step
1: Initialize the countdown value
let
countdown = 10;
// Step
2: Create an interval that runs every second
let timer
= setInterval(function() {
console.log(countdown);
countdown--; // Decrement the countdown value
// Step 3: Stop the interval when countdown
reaches 0
if (countdown < 0) {
clearInterval(timer); // Stop the interval
console.log("Time's up!");
}
}, 1000);
// Executes every 1000 milliseconds (1 second)
Explanation:
- setInterval() is
used to execute the function repeatedly every second.
- The
countdown variable is decremented each second.
- clearInterval() is
called when the countdown reaches 0 to stop the interval.
- The
message "Time's up!" is displayed when the countdown finishes.
Assignment
3: Stop the setInterval() Timer After a Condition is Met
Problem:
Write a JavaScript program that starts a timer that increments a counter every
1 second. The timer should stop after 5 seconds.
Solution:
javascript
Copy code
// Step
1: Initialize a counter variable
let
counter = 0;
// Step
2: Set an interval that increments the counter every second
let
intervalID = setInterval(function() {
counter++;
console.log(`Count: ${counter}`);
// Step 3: Stop the interval after 5 seconds
if (counter === 5) {
clearInterval(intervalID); // Stop the
interval
console.log("Stopped after 5
counts.");
}
}, 1000);
// Executes every 1000 milliseconds (1 second)
Explanation:
- setInterval() is
used to increment the counter every second.
- When
the counter reaches 5, clearInterval() is called to stop the timer.
- This
will log the count every second and stop after 5 seconds.
Assignment
4: Delayed Function Call Using setTimeout()
Problem:
Create a JavaScript program that simulates a delayed greeting. After a 2-second
delay, the message "Hello, welcome to JavaScript!" should be
displayed in the console.
Solution:
javascript
Copy code
// Step
1: Set a timeout that delays the function call by 2 seconds
setTimeout(function()
{
// Step 2: Display the greeting message after
the delay
console.log("Hello, welcome to
JavaScript!");
}, 2000);
// 2000 milliseconds = 2 seconds
Explanation:
- setTimeout() is
used here to delay the execution of the greeting message.
- The
anonymous function will log "Hello, welcome to JavaScript!" to
the console after a 2-second delay.
Assignment
5: Toggle Button Visibility Using setInterval()
Problem:
Create a JavaScript program where a button’s visibility is toggled every 3
seconds using setInterval(). The button should alternate between visible and
hidden states.
Solution:
html
Copy code
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Toggle Button
Visibility</title>
<style>
#toggleButton {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button
id="toggleButton">Click Me!</button>
<script>
// Step 1: Get the button element
let button =
document.getElementById('toggleButton');
// Step 2: Set an interval to toggle the
visibility every 3 seconds
let visibilityToggle = setInterval(function()
{
// Toggle the visibility of the button
button.style.visibility =
(button.style.visibility === 'hidden') ? 'visible' : 'hidden';
}, 3000); // 3000 milliseconds = 3 seconds
</script>
</body>
</html>
Explanation:
- setInterval() is
used to run a function every 3 seconds that toggles the visibility of the
button.
- The
button's visibility style is checked and switched between hidden and
visible.
Assignment
6: Auto-Refresh Page Using setInterval()
Problem:
Write a JavaScript program that automatically refreshes the web page every 10
seconds using setInterval().
Solution:
javascript
Copy code
// Step
1: Set an interval that refreshes the page every 10 seconds
setInterval(function()
{
// Step 2: Refresh the page
location.reload();
},
10000); // 10000 milliseconds = 10 seconds
Explanation:
- setInterval() is
used to call location.reload(), which refreshes the page every 10 seconds.
- The
setInterval() function is called with a delay of 10000 milliseconds (10 seconds).
Assignment
7: Canceling a Timeout Using clearTimeout()
Problem:
Create a JavaScript program that sets a timeout to display an alert after 5
seconds. However, cancel the timeout after 2 seconds, so the alert will not be
shown.
Solution:
javascript
Copy code
// Step
1: Set a timeout to display an alert after 5 seconds
let
timeoutID = setTimeout(function() {
alert("This message will never be
shown.");
}, 5000);
// Step
2: Cancel the timeout after 2 seconds
setTimeout(function()
{
clearTimeout(timeoutID); // Stop the timeout
from executing
console.log("Timeout was
canceled.");
}, 2000);
// 2000 milliseconds = 2 seconds
Explanation:
- setTimeout() is
used to set an alert to show after 5 seconds.
- clearTimeout() is
called after 2 seconds to cancel the timeout, preventing the alert from
appearing.
Assignment
8: Stop Repeated Action Using clearInterval()
Problem:
Write a program that repeatedly changes the background color of the page every
2 seconds using setInterval(). The color change should stop after 10 seconds.
Solution:
javascript
Copy code
// Step
1: Set an interval to change the background color every 2 seconds
let
colorChangeInterval = setInterval(function() {
// Change the background color to a random
color
document.body.style.backgroundColor =
`hsl(${Math.random() * 360}, 100%, 50%)`;
}, 2000);
// 2000 milliseconds = 2 seconds
// Step
2: Stop the interval after 10 seconds
setTimeout(function()
{
clearInterval(colorChangeInterval); // Stop
the color change
console.log("Color change
stopped.");
},
10000); // 10000 milliseconds = 10 seconds
Explanation:
- setInterval() is
used to change the background color of the page every 2 seconds.
- clearInterval() is
called after 10 seconds to stop the color change.
These assignments provide a good
foundation for understanding timing events in JavaScript. The use of setTimeout(),
setInterval(), clearTimeout(), and clearInterval() in various contexts will
help students gain a deeper understanding of how to work with timed events in
web development.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Here are more assignments based
on JavaScript Timing Events with step-by-step solutions and explanations:
Assignment
9: Delayed Image Change Using setTimeout()
Problem:
Write a JavaScript program that changes the image source after 4 seconds.
Initially, an image should be displayed, and after 4 seconds, the image should
change to a new one.
Solution:
html
Copy code
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Delayed Image
Change</title>
</head>
<body>
<img id="myImage"
src="image1.jpg" alt="Initial Image"
width="300">
<script>
// Step 1: Set a timeout to change the
image source after 4 seconds
setTimeout(function() {
document.getElementById('myImage').src = 'image2.jpg'; // Change image
source
}, 4000); // 4000 milliseconds = 4
seconds
</script>
</body>
</html>
Explanation:
- setTimeout() is
used to change the src attribute of the image element after 4 seconds.
- Initially,
image1.jpg is displayed, but after 4 seconds, it switches to image2.jpg.
Assignment
10: Repeatedly Change Background Color with setInterval()
Problem:
Create a JavaScript program that changes the background color of a webpage
every 3 seconds. After 15 seconds, stop changing the background color.
Solution:
javascript
Copy code
// Step
1: Initialize an interval to change background color every 3 seconds
let
intervalID = setInterval(function() {
document.body.style.backgroundColor =
`hsl(${Math.random() * 360}, 100%, 50%)`; // Random color
}, 3000);
// 3000 milliseconds = 3 seconds
// Step
2: Stop the color change after 15 seconds
setTimeout(function()
{
clearInterval(intervalID); // Stop the
interval
console.log("Background color change
stopped.");
},
15000); // 15000 milliseconds = 15 seconds
Explanation:
- setInterval()
changes the background color every 3 seconds to a random color using the
hsl function.
- clearInterval()
stops the interval after 15 seconds, preventing further color changes.
Assignment
11: Count Down from 10 to 1 Using setInterval()
Problem:
Write a program that counts down from 10 to 1 using setInterval(). Display the
current count in the console every second. Once it reaches 1, stop the
interval.
Solution:
javascript
Copy code
// Step
1: Initialize the counter to 10
let
countdown = 10;
// Step
2: Create an interval that runs every 1 second
let
countdownInterval = setInterval(function() {
console.log(countdown); // Display the
current countdown
countdown--; // Decrement the countdown
// Step 3: Stop the interval when countdown
reaches 0
if (countdown < 1) {
clearInterval(countdownInterval); //
Stop the interval
console.log("Countdown
finished!");
}
}, 1000);
// Executes every 1000 milliseconds (1 second)
Explanation:
- setInterval()
prints the countdown to the console every second.
- The
countdown is decremented, and once it reaches 0, clearInterval()
stops the interval.
Assignment
12: Delayed Function Call with setTimeout()
Problem:
Create a JavaScript function that accepts a name as an argument and displays a
greeting after a delay of 2 seconds.
Solution:
javascript
Copy code
// Step
1: Create a function that accepts a name as argument
function
greetUser(name) {
// Step 2: Use setTimeout to delay the
greeting message
setTimeout(function() {
console.log(`Hello, ${name}! Welcome to
JavaScript.`);
}, 2000); // 2000 milliseconds = 2 seconds
}
// Step
3: Call the function with a name
greetUser('John');
Explanation:
- setTimeout()
delays the greeting message by 2 seconds.
- The
greetUser function takes a name as input and displays a greeting after 2
seconds.
Assignment
13: Stop Interval on Button Click
Problem:
Create a webpage with a button. When the button is clicked, the webpage's
background color changes every 2 seconds. After 10 seconds, stop the color
change automatically.
Solution:
html
Copy code
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Stop Interval on Button
Click</title>
</head>
<body>
<button
id="startButton">Start Color Change</button>
<script>
let intervalID;
// Step 1: Event listener for button
click
document.getElementById('startButton').addEventListener('click',
function() {
// Step 2: Start changing
background color every 2 seconds
intervalID = setInterval(function()
{
document.body.style.backgroundColor = `hsl(${Math.random() * 360}, 100%,
50%)`; // Random color
}, 2000); // 2000 milliseconds = 2
seconds
// Step 3: Automatically stop the
interval after 10 seconds
setTimeout(function() {
clearInterval(intervalID); //
Stop the interval
console.log("Background
color change stopped.");
}, 10000); // 10000 milliseconds =
10 seconds
});
</script>
</body>
</html>
Explanation:
- When
the button is clicked, setInterval() starts changing the background
color every 2 seconds.
- setTimeout()
stops the color change after 10 seconds by calling clearInterval().
Assignment
14: Display Current Time Every Second Using setInterval()
Problem:
Write a program that displays the current time (in hours, minutes, and seconds)
every second on the webpage.
Solution:
html
Copy code
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Current Time
Display</title>
</head>
<body>
<h1>Current Time: <span
id="time"></span></h1>
<script>
// Step 1: Function to format time
(HH:MM:SS)
function displayTime() {
let now = new Date();
let hours =
now.getHours().toString().padStart(2, '0');
let minutes =
now.getMinutes().toString().padStart(2, '0');
let seconds =
now.getSeconds().toString().padStart(2, '0');
document.getElementById('time').textContent =
`${hours}:${minutes}:${seconds}`;
}
// Step 2: Display the time every
second
setInterval(displayTime, 1000); // 1000
milliseconds = 1 second
</script>
</body>
</html>
Explanation:
- The
displayTime() function gets the current time and formats it to HH:MM:SS.
- setInterval() is
used to call the displayTime() function every second, updating the
displayed time.
Assignment
15: Random Quote Every 5 Seconds
Problem:
Write a program that displays a random quote every 5 seconds. You can store the
quotes in an array and display one randomly each time.
Solution:
javascript
Copy code
// Step
1: Create an array of quotes
const
quotes = [
"The only limit to our realization of
tomorrow is our doubts of today.",
"Life is what happens when you're busy
making other plans.",
"To be yourself in a world that is
constantly trying to make you something else is the greatest
accomplishment.",
"It does not matter how slowly you go
as long as you do not stop.",
"In three words I can sum up
everything I've learned about life: it goes on."
];
// Step
2: Set an interval to display a random quote every 5 seconds
setInterval(function()
{
let randomIndex = Math.floor(Math.random()
* quotes.length); // Random index
console.log(quotes[randomIndex]); //
Display random quote
}, 5000);
// 5000 milliseconds = 5 seconds
Explanation:
- An
array of quotes is created.
- setInterval() is
used to display a random quote from the array every 5 seconds by selecting
a random index using Math.random().
These additional assignments
provide a deeper understanding of how to manipulate time-based events in
JavaScript. By practicing with these examples, students will develop a solid
foundation in handling delays and intervals for dynamic user experiences.
