Lecture Notes On Day 23
JavaScript Timing Events
Objective:
By the end of this lesson,
students will understand how to work with time-based events in JavaScript. This
includes setting up delays for actions, repeating actions at intervals, and
clearing timers when necessary.
Introduction
to Timing Events:
In JavaScript, there are several
methods for handling events based on time. This allows us to perform actions
after a delay or repeatedly at regular intervals. These methods are useful for
animations, game loops, delayed responses, or periodic updates like updating a
clock, fetching data, or updating user interfaces.
JavaScript provides three main
functions for time-based actions:
- setTimeout()
- setInterval()
- clearTimeout()
- clearInterval()
Let’s look into each of these
functions in detail.
1.
setTimeout()
setTimeout() is a built-in
JavaScript function that is used to execute a block of code after a specified
amount of time (in milliseconds).
Syntax:
setTimeout(function, delay);
- function:
This is the function or code that will run after the delay.
- delay:
The time (in milliseconds) to wait before executing the code.
Example:
setTimeout(function()
{
console.log("This message will display
after 3 seconds.");
}, 3000);
// 3000 milliseconds = 3 seconds
In this example, the message
"This message will display after 3 seconds." will be logged to the
console after a delay of 3 seconds.
Explanation:
- setTimeout()
takes two parameters: the first is the code (or function) you want to
execute, and the second is the time delay (in milliseconds).
- After
the specified time delay, the function inside setTimeout() will execute.
2.
setInterval()
setInterval() is similar to
setTimeout(), but instead of running the function once after the delay, it runs
the function repeatedly at the specified interval.
Syntax:
setInterval(function, interval);
- function:
The function or block of code that will execute repeatedly.
- interval:
The time (in milliseconds) between each execution of the function.
Example:
setInterval(function() {
console.log("This message will display
every 2 seconds.");
}, 2000);
// 2000 milliseconds = 2 seconds
In this example, the message
"This message will display every 2 seconds." will be logged to the
console every 2 seconds.
Explanation:
- setInterval()
runs the function at regular intervals, which continue until you stop them
manually.
- The
second parameter (interval) defines how often the function runs (in
milliseconds).
3.
Clearing Timers: clearTimeout() and clearInterval()
Sometimes, you may need to stop
the execution of a setTimeout() or setInterval() function before it finishes.
To do this, JavaScript provides two methods: clearTimeout() and
clearInterval().
- clearTimeout():
Stops a timeout that was set with setTimeout().
- clearInterval():
Stops an interval that was set with setInterval().
Syntax
for clearTimeout():
clearTimeout(timeoutID);
- timeoutID:
The ID returned by setTimeout() when it was initially called.
Syntax for clearInterval():
clearInterval(intervalID);
- intervalID:
The ID returned by setInterval() when it was initially called.
Example
with clearTimeout():
let timeoutID = setTimeout(function() {
console.log("This message won't be shown
because we canceled it.");
}, 3000);
// Cancel
the timeout before it executes
clearTimeout(timeoutID);
In this example, even though we
set a timeout for 3 seconds, the clearTimeout() method prevents the function
from executing.
Example
with clearInterval():
let intervalID = setInterval(function() {
console.log("This message will stop
after 5 seconds.");
}, 1000);
// Stop
the interval after 5 seconds
setTimeout(function()
{
clearInterval(intervalID);
}, 5000);
Here, the message will display
every second, but after 5 seconds, the clearInterval() method will stop the
interval.
When to Use Timing Events:
1. setTimeout():
o
Use when you need to delay an action for a specific
amount of time. For example, you can use it to display a message after a short
delay or run a function after waiting for user input.
o
Example: Delayed animations, alert messages, or
timeout functions.
2. setInterval():
o
Use when you need to perform an action at regular
intervals, like updating a clock, refreshing data from an API, or repeating
animations.
o
Example: Updating a live score, displaying
real-time clock, or fetching new data periodically.
3. clearTimeout()
and clearInterval():
o
Use these methods to stop a timer before it
executes or to stop a repeated action that was previously set with setTimeout()
or setInterval().
o
Example: Stopping a repeated animation or canceling
a delayed action based on user input.
Practical
Examples
1. Creating
a Countdown Timer Using setTimeout()
function countdown(seconds) {
console.log(`Countdown starting from
${seconds}`);
let timer = setInterval(function() {
seconds--;
console.log(seconds);
if (seconds <= 0) {
clearInterval(timer);
console.log("Time's up!");
}
}, 1000);
}
countdown(5);
// Countdown from 5 seconds
In this example, the countdown
starts from 5 seconds, printing each second until it reaches 0. At that point,
the timer is cleared.
2. Repeating Actions Using setInterval()
let counter = 0;
let
interval = setInterval(function() {
counter++;
console.log(`Count: ${counter}`);
if (counter === 5) {
clearInterval(interval); // Stop after 5
counts
}
}, 1000);
// Executes every 1 second
This example will log the count
every second, but stop when it reaches 5.
Key
Takeaways:
- setTimeout()
runs a function after a specified delay (once).
- setInterval()
runs a function repeatedly at specified intervals.
- clearTimeout() and
clearInterval() are used to stop timers.
- Use
setTimeout() for delays and setInterval() for repeated actions.
- These
timers are extremely useful in building interactive features such as
animations, live updates, and game loops.
Practice
Exercises:
1. Exercise
1: Use
setTimeout() to display a message after 3 seconds.
2. Exercise
2: Use
setInterval() to update a counter every 1 second.
3. Exercise
3: Create
a countdown timer that stops when it reaches 0 using both setInterval() and clearInterval().
4. Exercise
4: Write a
program that runs a task repeatedly every 2 seconds and stops after 10
repetitions using setInterval() and clearInterval().
Conclusion:
Timing events in JavaScript allow
developers to introduce delays, intervals, and timed behaviors in their web
applications. By mastering setTimeout(), setInterval(), and the clearing
mechanisms, students can enhance the interactivity and dynamism of their
websites and applications.
