JavaScript Timing
Control code execution with timers
â° What is JavaScript Timing?
JavaScript timing events allow you to execute code at specified time intervals. Use setTimeout() for delays and setInterval() for repeated execution.
// Execute after 3 seconds
setTimeout(function() {
console.log("Hello after 3 seconds!");
}, 3000);
// Execute every 2 seconds
setInterval(function() {
console.log("Repeating message");
}, 2000);
Output:
Hello after 3 seconds! (after 3 seconds)
Repeating message (every 2 seconds)
Timing Methods
setTimeout
Execute code after a delay
setTimeout(func, delay)
setInterval
Execute code repeatedly
setInterval(func, interval)
clearTimeout
Cancel a setTimeout
clearTimeout(timeoutId)
clearInterval
Stop a setInterval
clearInterval(intervalId)
đš setTimeout() Method
Execute code once after a specified delay:
// Basic setTimeout
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
// setTimeout with arrow function
setTimeout(() => {
console.log("Arrow function after 1 second");
}, 1000);
// setTimeout with parameters
function greetUser(name, age) {
console.log(`Hello ${name}, you are ${age} years old`);
}
setTimeout(greetUser, 3000, "John", 25);
// Store timeout ID for cancellation
let timeoutId = setTimeout(() => {
console.log("This might not run");
}, 5000);
Output:
Arrow function after 1 second (after 1s)
This runs after 2 seconds (after 2s)
Hello John, you are 25 years old (after 3s)
đš setInterval() Method
Execute code repeatedly at specified intervals:
// Basic setInterval
let counter = 0;
let intervalId = setInterval(function() {
counter++;
console.log("Count: " + counter);
// Stop after 5 counts
if (counter >= 5) {
clearInterval(intervalId);
console.log("Interval stopped");
}
}, 1000);
// Digital clock example
function updateClock() {
let now = new Date();
let time = now.toLocaleTimeString();
console.log("Current time: " + time);
}
// Update every second
let clockInterval = setInterval(updateClock, 1000);
Output:
Count: 1 (after 1s)
Count: 2 (after 2s)
...
Count: 5 (after 5s)
Interval stopped
đš Clearing Timers
Stop timers before they execute:
// Clear timeout
let myTimeout = setTimeout(() => {
console.log("This will not run");
}, 3000);
// Cancel the timeout
clearTimeout(myTimeout);
console.log("Timeout cancelled");
// Clear interval
let myInterval = setInterval(() => {
console.log("Repeating...");
}, 1000);
// Stop after 5 seconds
setTimeout(() => {
clearInterval(myInterval);
console.log("Interval stopped");
}, 5000);
Output:
Timeout cancelled
Repeating... (5 times)
Interval stopped
đš Practical Examples
Real-world timing applications:
// Countdown timer
function countdown(seconds) {
let timer = setInterval(() => {
console.log(seconds + " seconds remaining");
seconds--;
if (seconds < 0) {
clearInterval(timer);
console.log("Time's up!");
}
}, 1000);
}
countdown(5);
// Auto-save feature
let autoSaveInterval;
function startAutoSave() {
autoSaveInterval = setInterval(() => {
console.log("Auto-saving document...");
// Save logic here
}, 30000); // Save every 30 seconds
}
function stopAutoSave() {
clearInterval(autoSaveInterval);
console.log("Auto-save stopped");
}
// Delayed page redirect
function redirectAfterDelay(url, seconds) {
console.log(`Redirecting to ${url} in ${seconds} seconds...`);
setTimeout(() => {
console.log("Redirecting now...");
// window.location.href = url;
}, seconds * 1000);
}
Output:
5 seconds remaining
4 seconds remaining
...
Time's up!