Selected Reading

JavaScript - Timer Functions

In JavaScript, timers are a very noteworthy feature. 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.

Why do we need Timer Functions

  • Timer functions are useful when you have to execute a piece of code after certain time.
  • Also, useful for scheduling task.
  • They are also used for repeating certain tasks.
  • Timer functions are also used for developing animations and games.

Types of Timer Function

There are two types of timer functions in JavaScript

  • setTimeout() - This function is used to execute the code once after a certain time is passed.
  • setInterval() - This function is used to execute the code repeatedly after a certain time.

The setTimeout() Function

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. This function takes two 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.

Syntax

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

let timeoutId = setTimeout(callback, delay);

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

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

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>

Press the Start Timer button to see the output.

Output

Following is the output of the above code −

Program execution started
The callTimer function executed
This function executed after some delay.

The setInterval() Function

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() function.

setInterval() takes two parameters:

  • callback - It is a function that setInterval() function call after every interval.
  • delay - It is the time in milliseconds to call the callback function after every interval.

Syntax

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

setInterval(callback, interval);

Note: 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 setInterval() 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 > 50) {
                  clearInterval(TimerId);
               }
            }, 1000);
         }
      </script>
   </body>
</html>

Output

Following is the output of the above code

count = 0
count = 1
.
.
.
count = 50

To avoid the infinite loop, we have used the if statement to check if the count is greater than 50 and kill the timer using the clearInterval() function. We will discuss the clearInterval() function in the next section.

Using clearInterval() functions to kill the Timer

After starting the timer, we need to stop that. We can use the clearInterval() function to stop the setInterval() function. The clearInterval() function takes the unique id returned by the setInterval() function and stops the timer.

Parameters:

  • TimerId: It is a unique id returned by either the setTimeOut() or setInterval() function.
// To stop the setInterval() function
clearInterval(TimerId);

Example for clearInterval function

In the example below, we call the function after every second using the setInterval() timer function. Also, we keep track of the count of how many 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>

Output

Following is the output of the above code

count = 0
count = 1
count = 2
count = 3

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.

Using clearTimeout() function to kill the Timer

After starting the timer, we need to stop that. We can use the clearTimeout() function to stop the setTimeOut() function.

Parameters:

  • TimerId: It is a unique id returned by either the setTimeOut() or setInterval() function.
// To stop the setTimeOut() function
clearTimeout(TimerId);

Example for clearTimeout function

In the example below, we have used the setTimeOut() function to call the callback function after 2000 milliseconds. Also, we have used the clearTimeout() function to kill the timer after 1000 milliseconds.

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

Output

Following is the output of the above code −

The callTimer function executed
Timer killed after 1000 milliseconds.

In the above output, users can observe that the callback function did not execute as we had killed the timer after 1000 milliseconds.

Advertisements