Call a Function Every N Seconds in TypeScript
Introduction
When dealing with real-time, interactive, or dynamic applications, you may need to run a function every N seconds in TypeScript. In this Byte, we'll go over exactly how to do that.
Why Use Time-Interval Function Calls?
There are a lot of different scenarios where you might want to execute a function at regular intervals. Consider a live dashboard that needs to refresh data every few seconds, a digital clock updating the time, or a game where certain actions need to be performed repeatedly. All these use cases require some kind of mechanism to call functions at a specified time interval. This is where JavaScript's (and thus TypeScript's) time-interval function calls can help you out.
What is the setInterval Function?
Let's first understand one of the key functions that makes all of this possible: setInterval
. This function is well-known Web API function and is supported by all modern browsers. It's used to repeatedly execute code after a designated amount of milliseconds.
Here's how it works:
setInterval(() => {
console.log("Hello, StackAbuse readers!");
}, 3000);
In this snippet, "Hello, StackAbuse readers!" will be printed to the console every 3000 milliseconds (or 3 seconds). The first argument to setInterval
is the function to be executed, and the second argument is the delay in milliseconds. Here the first argument is just a simple arrow function that executes console.log
.
Note: setInterval
executes the function repeatedly at regular intervals. If you need to execute a function only once, you'll need to use another function: setTimeout
.
Call a Function Every N Seconds
Now, let's see how we can actually use setInterval
to call a function every N seconds. The setInterval
function works similarly to setTimeout
, but instead of executing the function once after the delay, it executes it repeatedly at the specified interval.
Here's how you can use it:
setInterval(() => {
console.log("This message will display every 2 seconds");
}, 2000);
In this example, "This message will display every 2 seconds" will be printed to the console every 2 seconds. The first argument to setInterval
is the function to be executed, and the second argument is the interval in milliseconds.
Remember, the interval you specify is the time between the function calls, not the time from the start of one call to the start of the next. This means that if your function takes a long time to execute, the intervals may end up being longer than you specified.
Note: To stop the function from being called, you can use the clearInterval
function. This function takes the identifier returned by setInterval
as an argument.
Here's an example:
let intervalId: NodeJS.Timeout = setInterval(() => {
console.log("This message will display every 2 seconds");
}, 2000);
// Stop the interval after 10 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 10000);
In this snippet, the message will be printed every 2 seconds, but will stop after 10 seconds. We've used setTimeout
to call clearInterval
after 10 seconds, stopping the interval.
In true TypeScript fashion, we've also declared the type for setInterval
's return value, which is formally NodeJS.Timeout
.
Link: For a more in-depth explanation of timers in JavaScript, check out our guide:
Common Errors and How to Fix Them
While using setTimeout
or setInterval
in TypeScript, a few common errors may arise. Let's take a look at some of these and how we can address them.
One common error is Uncaught ReferenceError: function is not defined
. This error can happen when the function you're trying to call with setTimeout
is not in the same scope. To fix this, just make sure that the function is accessible in the scope where setTimeout
/setInterval
is called.
function printMessage() {
console.log('Hello, StackAbuse!');
}
setTimeout(printMessage, 2000); // This will work
Another possible error is Uncaught TypeError: this.method is not a function
. This error can happen when this
inside the callback function doesn't refer to what you expect it to. JavaScript's this
can be a bit confusing, especially when dealing with callbacks. One way to fix this is by using an arrow function, which lexically binds this
.
class Printer {
message: string = 'Hello, StackAbuse!';
printMessage = () => {
console.log(this.message);
}
}
let printer = new Printer();
setTimeout(printer.printMessage, 2000); // This will work
Alternatives to setTimeout
Although setTimeout
is a powerful function, there are other ways to schedule tasks in TypeScript. One such alternative is setInterval
.
setInterval
works similarly to setTimeout
, but instead of executing the function once after a delay, it executes the function repeatedly at the specified interval.
setInterval(() => {
console.log('This message will repeat every 2 seconds');
}, 2000);
Another alternative is the requestAnimationFrame
function. This is particularly useful for animations, as it calls a function before the next repaint, allowing for smoother animations.
function animate() {
console.log('Animating...');
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
This one is specific to rendering use-cases, so it's usefulness is limited to that.
Conclusion
And there you have it, a Byte-sized guide to calling a function every N seconds in TypeScript. We've covered how to perform this function, some common errors you might encounter and their fixes, and looked at alternatives to setTimeout
.