How to schedule tasks using JavaScript Timers and Intervals
Gloria Tejuosho
Posted on July 1, 2024
Introduction
JavaScript is a dynamic language that allows web developers to add interactive features to web applications. Among its built-in functions are setTimeout
and setInterval
, used for scheduling tasks and managing timing within applications.
In this article, we will examine how the setTimeout
and setInterval
functions work and gain hands-on experience through practical examples.
Before proceeding, it's essential to have a basic understanding of JavaScript. You can refer to this article if you need to.
setInterval and setTimeout
setInterval
and setTimeout
are both essential for managing timing in JavaScript applications. However, these functions serve different purposes and have distinct use cases.
Let's get into each function's specific use cases and understand when to appropriately use them in our applications.
setInterval
setInterval
is a method that repeatedly executes a code at intervals defined by a specified time(In milliseconds).
It ensures that the code runs each time the specified interval elapses.
setInterval syntax
setInterval(function, delay, param1, param2, ...)
Function: The code to be executed.
Delay: The specified interval for the code to execute.
param1, param2: Optional parameters to be passed to the function.
Example 1: Using the setInterval function to display "Hello" after every second.
const greetings= setInterval ( function (){
console.log("Hello");
}, 1000)
Explanation
setInterval
takes two parameters: An anonymous function that logs "Hello" to the console, and a specified time interval of 1000 milliseconds which equals 1 second.
greetings
: A variable that holds the interval Id returned by the setInterval function.
Example 2: Create a count down timer with hours, minutes, and seconds.
Step 1: Set up the html
file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Change Style</title>
</head>
<body>
<div id="countdown"></div>
<script src=app.js>
</script>
</body>
</html>
Step 2: Include JavaScript code to achieve the countdown timer.
let timeRemaining = {
hours: 2,
minutes: 30,
seconds: 0
};
// Display the initial time
document.getElementById("countdown").innerHTML = `${timeRemaining.hours} hours, ${timeRemaining.minutes} minutes, ${timeRemaining.seconds} seconds`;
// Update the countdown every second
const countdownTimer = setInterval(function() {
// Convert the time to seconds
let totalSeconds = timeRemaining.hours * 3600 + timeRemaining.minutes * 60 + timeRemaining.seconds;
// Decrement the time by 1 second
totalSeconds--;
// Convert the time back to hours, minutes, and seconds
timeRemaining.hours = Math.floor(totalSeconds / 3600);
timeRemaining.minutes = Math.floor((totalSeconds % 3600) / 60);
timeRemaining.seconds = totalSeconds % 60;
// Display the updated time
document.getElementById("countdown").innerHTML = `${timeRemaining.hours} hours, ${timeRemaining.minutes} minutes, ${timeRemaining.seconds} seconds`;
// Check if the countdown is complete
if (totalSeconds <= 0) {
alert("Countdown complete!");
}
}, 1000);
-
timeRemaining
object that holds the remaining number of times in the countdown. Display the initial time by accessing
timeRemaining
element and updating theDom
with the Id "countdown".setInterval
creates an anonymous function and a specified time interval that runs every second.-
Inside the anonymous function:
- The
totalSeconds
variable converts the remaining time into seconds. -
totalSeconds --
: Decreases the time by 1 second. - Convert the time back to hours, minutes, and seconds.
- Use the
Math.floor
method to round down each value to the nearest whole number. - Update the
Dom
element with the updated time. - Use the conditional "If" statement to check if the countdown Is complete and a pop alert message if not so.
- The
This example demonstrates the use of setInterval
to create a countdown timer that updates every second, with hours, minutes, and seconds displayed.
clearInterval
This is a method that clears the function that was previously declared in the setInterval
. It clears the function in the setInterval
when it's no longer needed.
clearInterval Syntax
clearInterval (intervalId)
clearInterval: The function used to cancel repeating intervals.
intervalId: The identifier of the interval to be cleared.
Example: Using the clearInterval
to remove the function in the setInterval
once the total seconds is less than or equal to zero.
if (totalSeconds <= 0) {
clearInterval (countdownTimer)
alert("Countdown complete!");
}
}, 1000);
In the example above,
setInterval
function created a countdown timer and clearInterval
removed the function once the total seconds reached zero.
Importance of using clearInterva
It keeps code clean and efficient making it easier to maintain and debug.
It prevents memory leaks by stopping background interval execution.
It clears unnecessary code execution once it is no longer needed.
setTimeout
Set timeout is a method that executes a task after a specified delayed time (in milliseconds). It executes the task only when the specified time elapses.
It calls the function once unlike the setInterval function that calls a function repeatedly.
setTimeout syntax
setTimeout(function, milliseconds...)
- function: The code to be executed after a specified delay.
- Milliseconds: The time delay before the function is executed.
Example 1: Use setTimeout to display "Welcome to my page" after 2 seconds.
setTimeout(function() {
alert("Welcome to my page");
}, 2000);
Explanation:
setTimeout
takes two parameters: An anonymous function that displays an alert with the message "Welcome to my page" and a delay time of 2000 milliseconds(or 2 seconds) before the function is executed.
Example 2: Use setTimeout
to display a list of messages after 2 seconds.
Step 1: Set the html elements.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Display Messages</title>
<link type="text/css" rel="style.css" href="stylesheet" >
</head>
<body>
<div id="message">Display Messages</div>
<button id="startBtn"> Start message sequence</button>
<script src=app.js> </script>
</body>
</html>
Step 2: Include JavaScript code.
const messages =[
"First message",
"Second message",
"Third message",
"Fourth message",
]
const startBtn = document.getElementById("startBtn");
const message = document.getElementById("message");
let messageIndex = 0;
let timer;
function messageFunction(){
if (messageIndex < messages.length){
message.textContent = messages[messageIndex];
messageIndex ++;
timer = setTimeout (messageFunction, 2000);
}
else{
message.textContent = "All messages displayed";
}
}
startBtn.addEventListener('click', function (){
messageIndex = 0;
messageFunction ();
});
Explanation:
messages: An array that contains the list of messages to be displayed.
startBtn: A variable that targets the start button.
message: A variable that targets the messages to be displayed.
messageIndex: A variable that holds the index of the messages to be displayed. Its initial value is set to 1.
messageFunction(): A function that checks for two conditions:
- If the messageIndex is less than the length of the messages to be displayed, then, it displays each messages after 2 seconds using the setTimeout method
- If this condition is not met, then it displays "All messages have been displayed".
Add an eventListener that invokes the messageFunction once the 'start button' is clicked.
This example demonstrates the use of setTimeout to display a list of messages every 2 seconds.
clearTimeout
clearTimeout
is a method that clears a timer that was previously created in the setTimeout
.
clearTimeout syntax
clearTimeout (setTimeoutId)
clearTimeout
: The function used to cancel a timeout.
setTimeoutId
: The identifier of the timer to be canceled.
Example: Use the clearTimeout to cancel the message sequence.
Step 1: Create a button to stop the message sequence.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title> Display Messages</title>
<link type="text/css" rel="style.css" href="stylesheet" >
</head>
<body>
<div id="message">Display Messages</div>
<button id="startBtn"> Start message sequence</button>
<button id="stopBtn"> Stop message sequence </button>
<script src=app.js> </script>
</body>
</html>
Step 2: Add clearTimeout to the 'stop' button
const messages =[
"First message",
"Second message",
"Third message",
"Fourth message",
]
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const message = document.getElementById("message");
let messageIndex = 0;
let timer;
function messageFunction(){
if (messageIndex < messages.length){
message.textContent = messages[messageIndex];
messageIndex ++;
timer = setTimeout (messageFunction, 2000);
}
else{
message.textContent = "All messages displayed";
}
}
startBtn.addEventListener('click', function (){
messageIndex = 0;
messageFunction ();
});
stopBtn.addEvenListener('click', function(){
clearTimeout (timer);
message.textContent = "Message sequence stopped!";
})
Explanation:
stopBtn: A variable that targets the 'stop button' element.
An eventListener
is added to the 'stop button ' which uses the clearTimeout
method to cancel the timeout.
This makes the message sequence stop once the stop button is clicked.
Importance of clearTimeout
- It clears the
setTimeout
method when it's no longer needed. - It prevents memory leaks by avoiding background execution.
- It makes code clean and easy to debug.
Best Practices
There are best practices to follow when using the setInterval
or the setTimeout
function to prevent errors and ensure clean, efficient code.
setInterval
Always use the
clearInterval
to stop intervals from running in the background.Store the
setInterval
function inside a variable to easily access it inside theclearSetTimeout
function.Use the
try
-catch
to handle and debug errors.
setTimeout
Always clear the
setTimeout
when it is no longer needed to prevent memory leaks.Set a reasonable amount of time when using
setTimeout
.
Avoid too short a time which can cause execution to occur suddenly and too long a time which can affect user experience.Store the
setTimeout
function in a variable to easily access it in theclearTimeout
function.
Conclusion
Knowing when to use the setInterval and setTimeout functions is crucial, and we have discussed the types of functions they perform, when to use them, and best practices to follow. You should be able to use them effectively in your code.
Posted on July 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.