Timers setTimeout And setInterval In JavaScript

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.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment