4.1 setTimeout Function
Timers in JavaScript let you perform certain actions at specified time intervals. The two main methods for working with timers are setTimeout() and setInterval(). They're used to run code with a delay or at regular intervals.
The setTimeout() method lets you execute a function once after a specified number of milliseconds. This is useful for delaying code execution.
Syntax:
const timeoutID = setTimeout(callback, delay, ...args);
Where:
callback: the function to be executeddelay: the delay in milliseconds before the function is executedargs: additional arguments to pass to thecallbackfunction
Example of using setTimeout():
// Function to be executed in 2 seconds
function greet() {
console.log('Hello, world!');
}
// Setting a timer
const timeoutID = setTimeout(greet, 2000);
4.2 Canceling a setTimeout Timer
If you need to cancel the execution of a function scheduled with setTimeout(), you can use the clearTimeout() method:
// Function to be executed in 2 seconds
function greet() {
console.log('Hello, world!');
}
// Setting a timer
const timeoutID = setTimeout(greet, 2000);
// Canceling the timer
clearTimeout(timeoutID);
Example with additional arguments:
// Function to be executed in 2 seconds with arguments
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Setting a timer with argument
const timeoutID = setTimeout(greet, 2000, 'Alice');
4.3 setInterval Function
The setInterval() method allows you to repeatedly execute a function at specified time intervals. This is useful for periodic execution of code.
Syntax:
const intervalID = setInterval(callback, delay, ...args);
Where:
callback: the function to be executeddelay: the interval in milliseconds between calls to the functionargs: additional arguments to pass to thecallbackfunction
Example of using setInterval:
// Function to be executed every 2 seconds
function greet() {
console.log('Hello, world!');
}
// Setting an interval
const intervalID = setInterval(greet, 2000);
4.4 Canceling a setInterval Interval
If you need to stop repeated execution of a function, you can use the clearInterval() method.
// Function to be executed every 2 seconds
function greet() {
console.log('Hello, world!');
}
// Setting an interval
const intervalID = setInterval(greet, 2000);
// Canceling the interval in 10 seconds
setTimeout(() => {
clearInterval(intervalID);
console.log('Interval cleared');
}, 10000);
Example with additional arguments:
// Function to be executed every 2 seconds with arguments
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Setting an interval with argument
const intervalID = setInterval(greet, 2000, 'Alice');
4.5 Practical Use Examples
Example 1: Auto-updating Time
<!DOCTYPE html>
<html>
<head>
<title>Auto-update Time</title>
</head>
<body>
<h1>Current Time</h1>
<div id="time"></div>
<script>
function updateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString();
document.getElementById('time').textContent = timeString;
}
// Update the time every second
updateTime();
setInterval(updateTime, 1000);
</script>
</body>
</html>
Example 2: Periodic Data Request
// Function to simulate data request
function fetchData() {
console.log('Fetching data...');
// Here you can make a real request to the server
}
// Execute data request every 10 seconds
const intervalID = setInterval(fetchData, 10000);
// Stop requests in 1 minute
setTimeout(() => {
clearInterval(intervalID);
console.log('Stopped fetching data');
}, 60000);
GO TO FULL VERSION