Explain the working of timers in JavaScript
In JavaScript, timers are used to execute a piece of code at a specific time or repeatedly after a certain interval. There are two types of timers in JavaScript:
- setTimeout(): This method is used to execute a piece of code once after a specified delay.
Syntax: setTimeout(function, delay)
Example:
setTimeout(function() {
console.log("Hello World!");
}, 3000);
In the above example, the function will be executed after a delay of 3 seconds (3000 milliseconds).
- setInterval(): This method is used to execute a piece of code repeatedly after a specified interval.
Syntax: setInterval(function, interval)
Example:
setInterval(function() {
console.log("Hello World!");
}, 1000);
In the above example, the function will be executed every 1 second (1000 milliseconds).
Both setTimeout() and setInterval() return a unique ID that can be used to stop the timer using the clearTimeout() or clearInterval() methods respectively.
Syntax: clearTimeout(id)
or clearInterval(id)
Example:
var timerId = setTimeout(function() {
console.log("Hello World!");
}, 3000);
clearTimeout(timerId);
In the above example, the setTimeout() method will be cancelled before the function is executed.