
JavaScript timer
The JavaScript can use timers to execute code at a specified time interval or after a certain delay. There are two commonly used timer functions: setTimeout()
and setInterval()
.
1. setTimeout():
The setTimeout()
function is used to execute a function or evaluate an expression after a specified delay.
Syntax:
setTimeout(function, delay);
Example:
function sayHello() {
console.log("Hello!");
}
// Execute the sayHello function after a delay of 2000 milliseconds (2 seconds)
setTimeout(sayHello, 2000);
In this example, the sayHello
function will be executed after a delay of 2 seconds.
2. setInterval():
The setInterval()
function is used to repeatedly execute a function or evaluate an expression at a specified interval.
Syntax:
setInterval(function, interval);
Example:
function sayHello() {
console.log("Hello!");
}
// Execute the sayHello function every 1000 milliseconds (1 second)
setInterval(sayHello, 1000);
In this example, the sayHello
function will be executed every 1 second.
Both setTimeout()
and setInterval()
return a unique identifier, known as the timer ID. You can use this ID to stop the timer using the clearTimeout()
or clearInterval()
functions.
Example:
var timerId = setTimeout(function() {
console.log("Timer finished!");
}, 5000);
// Stop the timer before it completes
clearTimeout(timerId);
In this example, the setTimeout()
function returns a timer ID that is stored in the timerId
variable. The clearTimeout()
function is then called to stop the timer before it completes.
Note: It’s important to clear timers when they are no longer needed to prevent memory leaks and unnecessary execution of code.