Last updated: Feb 27, 2024
Reading timeยท2 min

Use the setInterval() method to call a function every N seconds in
TypeScript.
The first parameter the method takes is the function that will be called on a timer and the second parameter is the delay in milliseconds.
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; // ๐๏ธ call function every 3 seconds setInterval(() => { logger('bobbyhadz.com'); }, seconds * 1000);

The 2 parameters we passed to the setInterval method are:
delay milliseconds. Note that the
first invocation happens after delay milliseconds (not instantly).1000 milliseconds in a second, so you can convert a second to milliseconds by multiplying by 1000.If I run the file from the code snippet above, I can see that the function is
invoked every 3 seconds.

The setInterval method returns an interval ID, which uniquely identifies the
interval and can be used to cancel the interval.
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; const intervalID = setInterval(() => { logger('bobbyhadz.com'); }, seconds * 1000); // ๐๏ธ if some condition is met // cancel the interval clearInterval(intervalID);

You can use the clearInterval method to cancel the interval.
The only parameter the method takes is the unique identifier of the interval.
The setInterval method is used to call a function repeatedly. If you only need
to call a function once after N seconds, use the setTimeout method
instead.
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; setTimeout(() => { logger('bobbyhadz.com'); }, seconds * 1000);

We called the logger function a single time, after 3 seconds.
Similarly to setInterval, the setTimeout
method returns a timeout ID, which you can use to cancel the timeout.
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; const timeoutID = setTimeout(() => { logger('bobbyhadz.com'); }, seconds * 1000); // ๐๏ธ if some condition is met // cancel the timeout clearTimeout(timeoutID);
The only parameter the clearTimeout method takes is the ID that uniquely
identifies the timeout.
If you need to pass a function as a parameter, check out the following article.