Introduction
JavaScript provides two primary functions to manage timed operations: setTimeout
and setInterval
.
setTimeout(function, delay)
: Executes a function once after a specified delay (in milliseconds).setInterval(function, interval)
: Repeatedly executes a function with a fixed time delay between each call (in milliseconds).
Basic Examples
1. setTimeout
Basic Example
// This code sets a timer that executes a function after 2 seconds (2000 milliseconds).
setTimeout(function() {
console.log('Hello after 2 seconds');
}, 2000);
2. setInterval
Basic Example
// This code sets an interval that executes a function every 1 second (1000 milliseconds).
setInterval(function() {
console.log('Hello every 1 second');
}, 1000);
Practical Examples
1. Practical setTimeout
Example
Using setTimeout
to create a simple webpage alert after a certain period of time.
// Function to show an alert after 5 seconds
function showAlert() {
alert("This is a delayed alert!");
}
// Setting the timeout
setTimeout(showAlert, 5000); // Alert will appear after 5 seconds
2. Practical setInterval
Example
Using setInterval
to create a digital clock on a webpage.
// Function to update time every second
function updateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString();
console.log(timeString);
}
// Setting the interval to update every second
setInterval(updateTime, 1000);
Advanced Usage
Clearing setTimeout
and setInterval
You can stop the execution of a setTimeout
or setInterval
before it occurs using the following functions:
clearTimeout(timeoutID)
: Stops the execution of asetTimeout
before it occurs.clearInterval(intervalID)
: Stops the execution of asetInterval
.
Example:
// Setting a timeout
let timeoutID = setTimeout(function() {
console.log('This will not run if clearTimeout is called before 3 seconds');
}, 3000);
// Clearing the timeout
// Uncomment the line below to test
// clearTimeout(timeoutID);
// Setting an interval
let intervalID = setInterval(function() {
console.log('This will stop after 5 seconds');
}, 1000);
// Clearing the interval after 5 seconds
setTimeout(function() {
clearInterval(intervalID);
}, 5000);
Conclusion
setTimeout
is useful for delaying a single operation.setInterval
is useful for repeating an operation at regular intervals.- Both can be controlled and stopped using
clearTimeout
andclearInterval
.
Experimenting with these functions in different scenarios will help you understand their behavior and how they can be applied effectively in real-world programming tasks.