Clean β’ Professional
JavaScript provides built-in timing functions that allow you to schedule code execution after a delay or repeatedly at fixed intervals. These functions are part of the Browser Object Model (BOM) and are accessible via the window object.
The two main timing methods are:
setTimeout() β Run a function once after a delay.setInterval() β Run a function repeatedly at fixed intervals.setTimeout() β Execute Once After DelayThe setTimeout() method calls a function once after a specified number of milliseconds.
Syntax:
const timeoutId = setTimeout(function, delay, param1, param2, ...);
function β The function to execute.delay β Time in milliseconds to wait before execution.clearTimeout().Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Run greet() after 2 seconds
const timeoutId = setTimeout(greet, 2000, "Alice");
Canceling a Timeout:
clearTimeout(timeoutId);
setInterval() β Execute RepeatedlyThe setInterval() method calls a function repeatedly at fixed time intervals.
Syntax:
const intervalId = setInterval(function, interval, param1, param2, ...);
function β The function to execute.interval β Time in milliseconds between each execution.clearInterval().Example:
function showTime() {
const now = new Date();
console.log(`Current time: ${now.toLocaleTimeString()}`);
}
// Run showTime() every 1 second
const intervalId = setInterval(showTime, 1000);
Canceling an Interval:
clearInterval(intervalId);
Example 1 β Delayed Alert:
setTimeout(() => {
alert("This message appears after 3 seconds!");
}, 3000);
Example 2 β Countdown Timer:
let count = 5;
const countdown = setInterval(() => {
console.log(count);
count--;
if(count < 0) {
clearInterval(countdown);
console.log("Time's up!");
}
}, 1000);
Example 3 β Passing Parameters:
function greetUser(name) {
console.log(`Hello, ${name}!`);
}
setTimeout(greetUser, 2000, "Bob"); // Executes after 2 secondsΒ