Call a function every N seconds using TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 4, 2022

banner

Check out my new book

Call a function every N seconds using TypeScript #

Use the setInterval() method to call a function every N seconds in TypeScript, e.g. setInterval(myFunction, seconds * 1000). 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.

index.ts
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; // 👇️ call function every 3 seconds setInterval(() => { logger('Hello world'); }, seconds * 1000);

The 2 parameters we passed to the setInterval method are:

  1. The function we want to invoke every delay milliseconds. Note that the first invocation happens after delay milliseconds (not instantly).
  2. The time in milliseconds to delay between invocations of the function.
There are a 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.

call function every n seconds

The setInterval method returns an interval ID, which unique identifies the interval and can be used to cancel the interval.

index.ts
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; const intervalID = setInterval(() => { logger('Hello world'); }, seconds * 1000); // 👇️ if some condition is met // cancel the interval clearTimeout(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.

index.ts
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; setTimeout(() => { logger('Hello world'); }, 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.

index.ts
function logger(message: string) { console.log(`Logger got called with: ${message}`); } const seconds = 3; const timeoutID = setTimeout(() => { logger('Hello world'); }, 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.