Explain the working of timers in JavaScript


In JavaScript, timers are a very noteworthy feature. As like the normal watch timer, we can start the timer at a time and execute the function or code in JavaScript after a particular time.

In simple terms, we can use the timer to execute the code after some delay. For example, when you visit some website, it shows the signup box after 3 to 4 minutes of your visit, and that we can achieve using JavaScript. We can set the delay timer to show the signup popup box.

Another good example of the timer in real life is ads inside the application. When you open any application, it starts showing ads after 2 to 3 minutes and changes the ads in the interval of 1 to 2 minutes.

So, there are two different functions to set timers in JavaScript, which we will explore in this tutorial.

Using the setTimeOut() function to execute the code after a particular time

The setTimeOut() function allows us to execute a code after a particular delay. However, it allows us to define the delay. It executes the code only once after a particular delay.

When the setTimeOut() function executes, it starts the timer, and after the particular delay, it executes the callback function.

Syntax

Users can follow the syntax below to use the setTimeOut() function.

let timeoutId = setTimeout(callback, delay);

In the above syntax, the callback function also can be an arrow function to execute.

Parameters

  • Callback – It is a function to execute after a delayed amount of time.

  • Delay – The delay is the time in the milliseconds to execute the callback function after that time.

Return value

The setTimeOut() function returns the unique id, which we can use to kill the timer.

Example

In the example below, when the user clicks on the Start Timer button, it will call the callTimer() function. Users can see that it prints the “callTimer function executed first”, and after 2000 milliseconds, it prints “This function executed after some delay” as the setTimeOut() function calls the callback function after 2000 milliseconds.

<html>
   <body>
      <h2> Using the setTimeOut() function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "callTimer()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         output.innerHTML += "Program execution started </br>";
         function callTimer() {
            output.innerHTML = "The callTimer function executed  <br/>";
            setTimeout(callback, 2000);
         }
         function callback() {
            output.innerHTML += "This function executed after some delay.";
         }
      </script>
   </body>
</html>

Using the setInterval() function to execute the function after every interval

The setTimeOut() function executes the callback function only once, but the setInterval() function executes the code after every interval that we have passed as a second parameter of the setInterval().

Syntax

Users can follow the syntax below to use the setInterval() function.

setInterval(callback, interval)

Parameters

  • Callback – It is a function that setInterval() function call after every interval.

  • Interval – It is the time in milliseconds to call the callback function after every interval.

Return value

The setInterval() function also returns the unique id like the setTimeout() function, which we can use to stop the timer.

Example

In this example, we have used the setInterval() function to call the callback function after every 1000 milliseconds. Users can observe that when they press the start timer button, the startInterval() function will execute and which will invoke setInterval() function. The setInterval() function call the callback function after every second.

<html>
   <body>
      <h2> Using the <i> setInterval() </i> function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "startInterval()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         let count = 0;
         output.innerHTML += "Program execution started </br>";
         
         // when user clicks on the button, startInterval() function will be called
         function startInterval() {
            output.innerHTML = "The callTimer function executed <br/>";
            
            // the setInterval() function will call the callback function after every second.
            setInterval(callback, 1000);
         }
         function callback() {
            output.innerHTML += "This function executed for " + count + " time </br>";
            
            // update the count to track of howmany times a callback is called.
            count = count + 1;
         }
      </script>
   </body>
</html>

Using the clearTimeOut() and clearInterval() functions to kill the timer

After starting the timer, we need to stop that, also. We can use the clearTimeOut() function to stop the setTimeOut() function and the clearInterval() function to stop the setInterval() function.

Syntax

// To stop the setTimeOut() function
clearTimeout(TimerId);

// To stop the setInterval() function
clearInterval(TimerId);

Parameters

  • TimerId – It is a unique id returned by either the setTimeOut() or setInterval() function.

Example

In the example below, we call the function after every second using the setInterval() timer function. Also, we keep track of the count of howmany times the callback function is invoked by the setInterval() function.

In the callback function, we use the if statement to check if the count is greater than three and kill the timer using the clearInterval() function.

<html>
   <body>
      <h2> Using the <i> clearInterval() </i> function </h2>
      <div id = "output"> </div>
      <button id = "btn" onclick = "startInterval()"> Start Timer </button>
      <script>
         let output = document.getElementById("output");
         let count = 0;
         let TimerId = "";
         function startInterval() {
            TimerId = setInterval(() => {
               output.innerHTML += "count = " + count + "<br/>";
               count += 1;
               if (count > 3) {
                  clearInterval(TimerId);
               }
            }, 1000);
         }
      </script>
   </body>
</html>

In the above output, users can observe that it prints till count = 3, as we had killed the timer when the count became greater than 3.

Updated on: 05-Jan-2023

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements