EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial setInterval TypeScript
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

setInterval TypeScript

setInterval TypeScript

Introduction to setInterval TypeScript

setInterval TypeScript is a method used to repeat specific function with every given time intervals. setInterval() will evaluate expressions or calls a function at certain intervals. This method will continue calling function until window is closed or the clearInterval() method is called and returns a non-zero number which identifies created timer or a numeric value. TypeScript has offered a number of functions that allow code to be executed asynchronously after a certain time intervals elapse and execute repeatedly until the user gives a stop. Asynchronous code runs on the main function.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,883 ratings)

Syntax of setInterval TypeScript

Given below is the syntax of setInterval() in TypeScript:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Or

let timer = setInterval(callback function, delay,[arg1, arg2, arg3, ...]);

  • As per the syntax, function() is actually the callback function to be executed for each millisecond.
  • time_in_milliseconds, involves the delay that the timer should actually have a delay between the execution of callback functions.
  • arg1, arg2, arg3, … are the arguments passed to callback function.
  • setInterval() function will return a non zero numeric that will identify created timer. It works similar to setTimeout() but executes callback repeatedly for each specific delay.

Examples of setInterval TypeScript

Given below are the examples of setInterval TypeScript:

Example #1: setInterval() timer

Code:

<!DOCTYPE html>
<body>
<p>Once this code is executed, after 5000 milliseconds, data is logged</p>
<p>New alert will open once the previous one is closed after 5 seconds! which actually stops timer!</p>
<script>
"use strict";
let timerId = setInterval(() => alert('10 seconds delay here!'), 5000);
setTimeout(() => { clearInterval(timerId); alert('Timer stops!'); }, 5000);
</script>
</body>
</html>

Output:

setInterval TypeScript 1

So here you have the input logged on after 5 seconds of the code execution.

setInterval TypeScript 2

And within another 5 seconds, timer is stopped as below.

setInterval TypeScript 3

setInterval() comes into the picture when the user wants to run code repeatedly, e.g., in cases of animation or any recursive algorithms.

It works in a similar way as setTimeout() but the only difference is that the function passed as the first parameter is repeatedly executed with no less than the milliseconds value given by the other argument. User can pass any number of parameters to the function that is being executed like subsequent parameters.

Example #2: setInterval() for displaying timer

Code:

<!DOCTYPE html>
<html>
<head>
<title>Clock using setInterval() method</title>
</head>
<body>
<p>Timer is ticking here!</p>
<p class="time"></p>
<script>
function displayTimer() {
let dateVal = new Date();
let timeVal = dateVal.toLocaleTimeString();
document.querySelector('.time').textContent = timeVal;
}
displayTimer();
const createClock = setInterval(displayTimer, 1000);
</script>
</body>
</html>

Output:

Here we are displaying timer with interval of 1 millisecond.

interval of 1 millisecond

In the output, it shows as a constant value, but on execution, you can see that timer will be ticking for each second i.e., the function used along with setInterval() is called repeatedly. Here, setInterval() method will return an identifiable value which can be used in further methods such as to cleat interval or stop timer. setInterval() timer will keep on running the code, until user does something to stop. Users should stop such kind as there may be errors and the browser will not be able to complete the other tasks. Returned value from setInterval() method is passed to clearInterval() method, to stop Intervals.

Recursion with setInterval() method: Interval time chosen includes time taken to execute the given part of code user wants to run. For e.g., let us say, code takes 60 milliseconds to run, hence the rest 40 milliseconds will end up as an interval.

Example #3: setInterval() for changing text color

Code:

<!DOCTYPE html>
<html>
<head>
<title>setInterval() to bring changes in text color, along with clearInterval to stop</title>
<script>
var interval;
function colorChange() {
interval = setInterval(text, 3000);
}
function text() {
var Ele = document.getElementById('boxID');
if(Ele.style.color === 'orange') {
Ele.style.color = 'blue'
} else {
Ele.style.color = 'orange'
}
}
function stopColorChange() {
clearInterval(interval);
}
</script>
</head>
<body onload="colorChange();">
<div id="boxID">
<p>Text color keeps changing for every interval</p>
</div>
<button onclick="stopColorChange();">Click here to Stop!</button>
</body>
</html>

Output:

setInterval TypeScript 5

Here, once this code is executed, after 3 milliseconds, text color will change to orange.

text color will change to orange

And after other 3 milliseconds, text color changes to blue, as below based on the if condition.

text color changes to blue

Once you click the stop button, changing text colors would stop.

Conclusion

With this, we shall conclude the topic ‘setInterval TypeScript’. We have seen what setInterval TypeScript is and explained how it works with few examples. We have seen the syntax of setInterval() method to implement programs. We also have clearInterval() method to stop the interval timer. The above examples will give a clear picture of setInterval() is to be implemented.

Recommended Articles

This is a guide to setInterval TypeScript. Here we discuss the introduction and examples of setInterval TypeScript for better understanding. You may also have a look at the following articles to learn more –

  1. TypeScript npm
  2. TypeScript Optional Chaining
  3. TypeScript Array of Objects
  4. TypeScript keyof Enum
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more