Timers setTimeout And setInterval In JavaScript: Hello everyone, welcome to the nkcoderz.com website.
Timers setTimeout And setInterval In JavaScript
In JavaScript, you can use the setTimeout
and setInterval
functions to execute a piece of code at a specified time interval.
The setTimeout
function is used to execute a piece of code once after a specified delay, while the setInterval
function is used to execute a piece of code repeatedly at a specified interval.
Here’s an example of how to use setTimeout
:
Code For setTimout Function
function showMessage() {
console.log('Hello, world!');
}
setTimeout(showMessage, 5000);
In this example, the showMessage
function is called after a delay of 5 seconds (5000 milliseconds).
Here’s an example of how to use setInterval
:
Code For setInterval Function
let count = 0;
function incrementCount() {
count++;
console.log(count);
}
setInterval(incrementCount, 1000);
In this example, the incrementCount
function is called every second (1000 milliseconds) to increment a counter and log its value to the console.
Both setTimeout
and setInterval
return a timer ID that can be used to cancel the execution of the code. To cancel a timer, you can use the clearTimeout
or clearInterval
function and pass in the timer ID as an argument.
Code For setTimout Function
Here’s an example of how to cancel a timer using clearTimeout
:
const timerId = setTimeout(showMessage, 5000);
clearTimeout(timerId);
In this example, the setTimeout
function returns a timer ID that is stored in the timerId
variable. The clearTimeout
function is used to cancel the execution of the showMessage
function before it is called.