Typescript

How to Use setInterval() in TypeScript and What’s its Appropriate Return Type?

The “setInterval()” function allows developers to repeatedly execute a specific piece of code or function after every fixed interval. This functionality makes it a perfect choice for implementing periodic tasks. It is also used to build a real-time user interface that is needed when it comes to fetch data periodically. The “setInterval()” is widely used for data updates from a server after a specified interval of time or to update a countdown timer.

This blog explains the implementation of the “setInterval()” function in TypeScript and its appropriate return type using following outline:

How to Use setInterval() in TypeScript?

The “setInterval()” function in TypeScript executes a specific function after every provided interval. It can be used for animation purposes and enables asynchronous behavior which prevents deadlock-like conditions. In addition, it performs background tasks that require continuous execution.

Syntax

The syntax for the “setInterval()” function in TypeScript is stated below:

let timer = setInterval(callbackFunc, timeInter, arg's...);

In the above syntax, “callbackFunc” is the specific function that is going to be executed after a specified time interval. The “timeInter” is the delay time or time interval and “arg’s” are the messages or values that can be passed to the “callbackFunc”.

Let’s have a look on couple of examples for a better explanation.

Example 1: Setting setInterval() Function

In this example, the “setInterval()” function is going to be utilized to print a dummy message on the console after a specific time interval:

<script>
 setInterval(() => {
 console.log('This message gets displayed after every 500 MilliSeconds.');
 }, 500);
</script>

In the above code, the “setInterval()” function is used which consists of two parameters. The first one is a callback function that performs specific tasks like displaying messages. The second parameter is the time interval after which the provided callback function gets invoked. For instance, the dummy message is going to be displayed on the console after “500” milliseconds.

After compilation:

The output shows that the provided message is displayed after every interval of 500 milli-seconds on the console.

Example 2: Setting setInterval() Function For Specified Time

To execute the “setInterval()” function for a specific time interval the “clearInterval()” function can be used. The “clearInterval()” specifically stops the execution cycle for the “setInterval()” function, as in the below example the “setInterval() runs for 10 iterations only:

<script>

 let k = 0;
 const timeInt = setInterval(() => {
  console.log(k + 1);
   if (++k == 10) {
    clearInterval(timeInt);
   }
  }, 1500);
</script>

Description of the above code:

  • First, the variable “k” is initialized with the value “0” and the variable “timeInt” is declared that contains the “setInterval()” function. This displays the updated value of “k” on the console by adding “1” to its value.
  • Inside it, the “if” statement is used that pre-increments the value of “k” and checks if the value gets equal to “10” or not. Whenever the “if” statement returns “true” the “clearInterval()” function gets used to clear the “setInterval()” function stored in the variable “timeInt”.
  • After that, provide the time interval of “1500” milliseconds to the “setInterval()” function’s second parameter.

After the compilation, the output will be as follows:

The above gif shows that the “setInterval()” function has displayed the messages for the specified number of times.

Example 3: Setting setInterval() Function to Apply Styling For Specified Time

The “setInterval()” function can be used to apply multiple styling to the specific elements after a provided time interval to provide an animation effect. It helps in creating responsive and intuitive designs. For instance, the color of the selected DOM element is changing after a specific time interval:

<div>
 <div id="demoEle">
  <h3>Linuxhint Text Color Changes</h3>
 </div>
 <button onclick="stopInterval();">Press to Stop!</button>
</div>
<script>
 var timeInt;
 function colorModify() {
  timeInt = setInterval(useCase, 1500);
  }
 function useCase() {
  var testEle = document.getElementById('demoEle');
  if(testEle.style.color === 'cyan') {
   testEle.style.color = 'red'
  } else {
  testEle.style.color = 'cyan'
  }
 }
 function stopInterval() {
  clearInterval(timeInt);
 }
</script>

Description of the above code:

  • First, the “h3” HTML element has been created inside the “div” element having an ID of “demoEle”. A button is also created that calls the “stopInterval()” function that stops the color changing over an element.
  • Inside the “<script>” tag, the “timeInt” named variable and the “colorModify()” function is created. That uses the “setInterval()” function to execute the “useCase” function after every “1500” milliseconds.
  • Now, define the “useCase()” function that retrieves the reference of selected HTML element having an ID of “demoEle” which gets stored in a “testEle” variable.
  • In addition, insert the “if\else” statement inside it that sets the color property to “cyan” and “red” periodically.
  • After that, define the “stopInterval()” function to clear the “setInterval()” function using the “clearInterval()” function.

Here is the output after the compilation:

The above gif shows that the color for the selected HTML element has been changing after specified time interval.

What is the Appropriate Return Type For “setInterval()” in TypeScript?

The appropriate return value for the “setInterval()” function in TypeScript is a numeric number or numeric ID and it can’t be equal to zero. This returned numeric ID gets passed to the “clearInterval()” function to stop the execution performed by the “setInterval()” function. It has similar behavior to “setTimeout()” but this function kills itself after a specified time period. In contrast, the “setInterval()” function needs to be cleared using the “clearInterval()” function.

We have covered how to use “setInterval()” method in TypeScript.

Conclusion

To use the “setInterval()” function in TypeScript, first define its first parameter which is a callback function that the developer wants to execute after regular intervals. Assign the delay time in milliseconds as the second parameter specifying the time interval after which the function gets executed. After that, the “setInterval()” function returns a numeric Identifier “ID” that can be used along the “clearInterval()” function to clear or stop the execution cycle. That is all about TypeScript’s “setInterval()” function.

About the author

Abdul Moeed

I'm a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I'm always eager to help others expand their understanding of technology.