Introduction
When coping with real-time, interactive, or dynamic purposes, it’s possible you’ll have to run a perform each N seconds in TypeScript. On this Byte, we’ll go over precisely how to do this.
Why Use Time-Interval Perform Calls?
There are a whole lot of completely different situations the place you may wish to execute a perform at common intervals. Take into account a stay dashboard that should refresh information each few seconds, a digital clock updating the time, or a sport the place sure actions should be carried out repeatedly. All these use instances require some form of mechanism to name features at a specified time interval. That is the place JavaScript’s (and thus TypeScript’s) time-interval perform calls can assist you out.
What’s the setInterval Perform?
Let’s first perceive one of many key features that makes all of this attainable: setInterval
. This perform is well-known Net API perform and is supported by all fashionable browsers. It is used to repeatedly execute code after a delegated quantity of milliseconds.
Here is the way it works:
setInterval(() => {
console.log("Howdy, StackAbuse readers!");
}, 3000);
On this snippet, “Howdy, StackAbuse readers!” might be printed to the console each 3000 milliseconds (or 3 seconds). The primary argument to setInterval
is the perform to be executed, and the second argument is the delay in milliseconds. Right here the primary argument is only a easy arrow perform that executes console.log
.
Notice: setInterval
executes the perform repeatedly at common intervals. If it is advisable to execute a perform solely as soon as, you may want to make use of one other perform: setTimeout
.
Name a Perform Each N Seconds
Now, let’s have a look at how we will truly use setInterval
to name a perform each N seconds. The setInterval
perform works equally to setTimeout
, however as a substitute of executing the perform as soon as after the delay, it executes it repeatedly on the specified interval.
Here is how you should use it:
setInterval(() => {
console.log("This message will show each 2 seconds");
}, 2000);
On this instance, “This message will show each 2 seconds” might be printed to the console each 2 seconds. The primary argument to setInterval
is the perform to be executed, and the second argument is the interval in milliseconds.
Keep in mind, the interval you specify is the time between the perform calls, not the time from the beginning of 1 name to the beginning of the following. Because of this in case your perform takes a very long time to execute, the intervals could find yourself being longer than you specified.
Notice: To cease the perform from being known as, you should use the clearInterval
perform. This perform takes the identifier returned by setInterval
as an argument.
Here is an instance:
let intervalId: NodeJS.Timeout = setInterval(() => {
console.log("This message will show each 2 seconds");
}, 2000);
// Cease the interval after 10 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 10000);
On this snippet, the message might be printed each 2 seconds, however will cease after 10 seconds. We have used setTimeout
to name clearInterval
after 10 seconds, stopping the interval.
In true TypeScript trend, we have additionally declared the sort for setInterval
‘s return worth, which is formally NodeJS.Timeout
.
Hyperlink: For a extra in-depth clarification of timers in JavaScript, take a look at our information:
Tips on how to use Timers and Occasions in Node.js
Frequent Errors and Tips on how to Repair Them
Whereas utilizing setTimeout
or setInterval
in TypeScript, just a few widespread errors could come up. Let’s check out a few of these and the way we will tackle them.
One widespread error is Uncaught ReferenceError: perform will not be outlined
. This error can occur when the perform you are making an attempt to name with setTimeout
will not be in the identical scope. To repair this, simply ensure that the perform is accessible within the scope the place setTimeout
/setInterval
known as.
perform printMessage() {
console.log('Howdy, StackAbuse!');
}
setTimeout(printMessage, 2000); // This may work
One other attainable error is Uncaught TypeError: this.methodology will not be a perform
. This error can occur when this
contained in the callback perform would not confer with what you count on it to. JavaScript’s this
is usually a bit complicated, particularly when coping with callbacks. One solution to repair that is through the use of an arrow perform, which lexically binds this
.
class Printer {
message: string = 'Howdy, StackAbuse!';
printMessage = () => {
console.log(this.message);
}
}
let printer = new Printer();
setTimeout(printer.printMessage, 2000); // This may work
Options to setTimeout
Though setTimeout
is a robust perform, there are different methods to schedule duties in TypeScript. One such different is setInterval
.
setInterval
works equally to setTimeout
, however as a substitute of executing the perform as soon as after a delay, it executes the perform repeatedly on the specified interval.
setInterval(() => {
console.log('This message will repeat each 2 seconds');
}, 2000);
One other different is the requestAnimationFrame
perform. That is notably helpful for animations, because it calls a perform earlier than the following repaint, permitting for smoother animations.
perform animate() {
console.log('Animating...');
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
This one is particular to rendering use-cases, so it is usefulness is restricted to that.
Conclusion
And there you have got it, a Byte-sized information to calling a perform each N seconds in TypeScript. We have lined the best way to carry out this perform, some widespread errors you may encounter and their fixes, and checked out alternate options to setTimeout
.