Borislav Hadzhiev
Last updated: Mar 4, 2022
Check out my new book
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.
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:
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 unique 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('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.
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.
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.