In JavaScript, you can create timers using the built-in functions setTimeout
and setInterval
. These functions allow you to execute a piece of code after a specified delay or at regular intervals, respectively.
Timers are useful in various scenarios, such as delaying the execution of a function, scheduling periodic updates, or implementing animations.
Using setTimeout:
setTimout()
The setTimeout
function allows you to execute a function after a specified delay (in milliseconds). The basic syntax for setTimeout
is:
setTimeout(function, delay);
where function
is the function you want to execute, and delay
is the time delay (in milliseconds) after which the function should be executed.
function showMessage() {
console.log("Timer completed!");
}
setTimeout(showMessage, 2000); // 2 seconds delay
clearTimeout()
The setTimeout
function returns a unique timer ID that can be used to cancel the execution of the function before it occurs, using the clearTimeout
function.
The basic syntax for clearTimeout
is as follows:
var timerId = setTimeout(function, delay);
clearTimeout(timerId);
Combined:
function showMessage() {
console.log("Timer completed!");
}
var timerId = setTimeout(showMessage, 2000); // 2 seconds delay
clearTimeout(timerId); // Cancel the timer
In this example, the showMessage
function will not be executed because the clearTimeout
function is called before the delay of 2000 milliseconds (2 seconds) is completed.
Using setInterval:
setInterval():
The setInterval
function allows you to execute a function at regular intervals. The basic syntax for setInterval
is as follows:
setInterval(function, delay);
where function
is the function you want to execute, and delay
is the time delay (in milliseconds) between each execution of the function.
function showMessage() {
console.log("Timer completed!");
}
var timerId = setInterval(showMessage, 1000); // 1 second interval
clearInterval():
The setInterval
function returns a unique timer ID that can be used to stop the repeated execution of the function, using the clearInterval
function.
The basic syntax for clearInterval
is as follows:
var timerId = setInterval(function, delay);
clearInterval(timerId);
Combined:
function showMessage() {
console.log("Timer completed!");
}
var timerId = setInterval(showMessage, 1000); // 1 second interval
// Stop the timer after 5 seconds
setTimeout(function () {
clearInterval(timerId);
}, 5000); // 5 seconds delay
In this example, the showMessage
function will be executed every 1000 milliseconds (1 second) using setInterval
. However, after 5 seconds (5000 milliseconds), the clearInterval
function is called to stop the repeated execution of the function.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.