Saturday, October 7, 2023
HomeProgrammingName a Operate Each N Seconds in TypeScript

Name a Operate Each N Seconds in TypeScript


Introduction

When coping with real-time, interactive, or dynamic functions, you might have to run a operate each N seconds in TypeScript. On this Byte, we’ll go over precisely how to try this.

Why Use Time-Interval Operate Calls?

There are numerous totally different situations the place you may need to execute a operate at common intervals. Think about a reside dashboard that should refresh knowledge each few seconds, a digital clock updating the time, or a sport the place sure actions must be carried out repeatedly. All these use instances require some sort of mechanism to name capabilities at a specified time interval. That is the place JavaScript’s (and thus TypeScript’s) time-interval operate calls can assist you out.

What’s the setInterval Operate?

Let’s first perceive one of many key capabilities that makes all of this potential: setInterval. This operate is well-known Internet API operate and is supported by all trendy browsers. It is used to repeatedly execute code after a delegated quantity of milliseconds.

This is the way it works:

setInterval(() => {
    console.log("Whats up, StackAbuse readers!");
}, 3000);

On this snippet, “Whats up, StackAbuse readers!” will probably be printed to the console each 3000 milliseconds (or 3 seconds). The primary argument to setInterval is the operate to be executed, and the second argument is the delay in milliseconds. Right here the primary argument is only a easy arrow operate that executes console.log.

Be aware: setInterval executes the operate repeatedly at common intervals. If it’s essential execute a operate solely as soon as, you may want to make use of one other operate: setTimeout.

Name a Operate Each N Seconds

Now, let’s examine how we will really use setInterval to name a operate each N seconds. The setInterval operate works equally to setTimeout, however as an alternative of executing the operate as soon as after the delay, it executes it repeatedly on the specified interval.

This 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” will probably be printed to the console each 2 seconds. The primary argument to setInterval is the operate to be executed, and the second argument is the interval in milliseconds.

Keep in mind, the interval you specify is the time between the operate calls, not the time from the beginning of 1 name to the beginning of the following. Because of this in case your operate takes a very long time to execute, the intervals might find yourself being longer than you specified.

Be aware: To cease the operate from being known as, you should use the clearInterval operate. This operate takes the identifier returned by setInterval as an argument.

This 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 will probably 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 vogue, we have additionally declared the kind 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

Widespread Errors and Tips on how to Repair Them

Whereas utilizing setTimeout or setInterval in TypeScript, a number of frequent errors might come up. Let’s check out a few of these and the way we will handle them.

One frequent error is Uncaught ReferenceError: operate will not be outlined. This error can occur when the operate you are making an attempt to name with setTimeout will not be in the identical scope. To repair this, simply ensure that the operate is accessible within the scope the place setTimeout/setInterval known as.

operate printMessage() {
    console.log('Whats up, StackAbuse!');
}

setTimeout(printMessage, 2000); // This can work

One other potential error is Uncaught TypeError: this.technique will not be a operate. This error can occur when this contained in the callback operate does not check with what you count on it to. JavaScript’s this generally is a bit complicated, particularly when coping with callbacks. One solution to repair that is through the use of an arrow operate, which lexically binds this.

class Printer {
    message: string = 'Whats up, StackAbuse!';

    printMessage = () => {
        console.log(this.message);
    }
}

let printer = new Printer();
setTimeout(printer.printMessage, 2000); // This can work

Options to setTimeout

Though setTimeout is a robust operate, there are different methods to schedule duties in TypeScript. One such various is setInterval.

setInterval works equally to setTimeout, however as an alternative of executing the operate as soon as after a delay, it executes the operate repeatedly on the specified interval.

setInterval(() => {
    console.log('This message will repeat each 2 seconds');
}, 2000);

One other various is the requestAnimationFrame operate. That is notably helpful for animations, because it calls a operate earlier than the following repaint, permitting for smoother animations.

operate animate() {
    console.log('Animating...');
    requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

This one is restricted to rendering use-cases, so it is usefulness is proscribed to that.

Conclusion

And there you will have it, a Byte-sized information to calling a operate each N seconds in TypeScript. We have lined easy methods to carry out this operate, some frequent errors you may encounter and their fixes, and checked out alternate options to setTimeout.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments