Tips for executing asynchronous functions repetitively in typescript?

Suppose I have the following setup:

class Foo {
    constructor(obj:number) {
         // execute "Run"
         // call "Run" again after 1 second following each completion
    }
    private async Run(obj:number):Promise<void> {
         // includes code that utilizes await
    }
}

Upon creating an instance of this class, my goal is to continuously run the Run function in an infinite loop. After each execution of Run, there should be a one-second delay before it runs again using the method setTimeout. Additionally, since Run does not return any value, it can be considered void.

How would I go about accomplishing this?

Answer №1

If you're looking to automate a process, this code snippet provides the necessary functions to achieve that goal.

class Foo {
    constructor(obj:number) {
       this.startOperation();
    }
    private async startOperation():Promise<void> {
         for(let i = 0;; i++) {
            await this.execute(i);
            await this.pause(1000);
         }
    }
    private pause(timeout: number): Promise<void> {
      return new Promise(res => setTimeout(res, timeout));
    }
    private async execute(obj:number):Promise<void> {
         // code here utilizes asynchronous functionality
    }
    
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Raycast failing to detect objects that have been displaced from their original starting position

I am facing a challenge with using a raycast to locate objects under the mouse cursor. The issue arises when the objects are not positioned at (0, 0, 0) as they cannot be detected by the raycast. Once I move the object to any other position, it no longer r ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Effortlessly glide through entire pages using the mouse wheel for seamless scrolling

I provide a seamless full-page scrolling experience using the mouse wheel. However, the scrollIntoView function does not seem to function within the @HostListener('wheel', ['$event']). Here is a snippet from app.component.html file: & ...

Struggling to grasp the error: "NDEFReader is not defined" in a Vue3 web application

In the process of developing a vue3 application, I am integrating the NFC Web API to facilitate reading and writing NFC Chips. My project utilizes typescript, vue routing, and pinia for smooth functionality. Everything runs smoothly when the application i ...

Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array. Here is the initial array of objects: "attentionSchedules": [ { "room": "1", ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Is there a way to toggle or collapse a table row with a unique identifier using Angular and Bootstrap?

Currently handling Angular and Bootstrap in my work, but facing challenges with table manipulation and collapsing rows. I fetch data from a database and showcase it in a dynamically generated table using *ngFor and two rows within an ng-container. My goal ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

The error message "Module not found" has appeared while searching from the root directory in VS Code

Struggling to resolve a module import issue in Visual Studio Code: https://i.sstatic.net/33tzW.png A demonstration of this problem can be found in a sample repository with the following directory structure: ➜ tree -I node_modules . ├── README.md ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

When utilizing useMachine in TypeScript, an error is thrown regarding incompatible types

While attempting to build my first example for a xstate finite machine by following the example on github.com/carloslfu/use-machine, I encountered a TypeScript error that halted my progress: Argument of type '{ actions: { sideEffect: () => void; } ...

How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition: export class MyService { doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) { // Function performs an action } } This service is utilized in a component as shown be ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

Utilizing Angular CDK to link several drop zones together using the cdkDropListConnectedTo directive

Currently in the process of designing a basic board interface with swim lanes similar to Jira swimlane or trello boards https://i.sstatic.net/7MBvm.png The red lines indicate the current flow The blue lines represent the flow that I aim to implement The ...

Ensuring User Authentication in Angular with Firebase: How to Dynamically Hide the Login Link in Navigation Based on User's Login Status

After successfully implementing Angular Firebase email and password registration and login, the next step is to check the user's state in the navigation template. If the user is logged in, I want to hide the login button and register button. I tried s ...

Tips for accessing $data in a Vue component that uses classes

Here is my component setup: interface Data { selectedOption: string; } @Component({ }) export default class OptionSelector extends Vue { public data(): Data { return { selectedOption: 'None', }; } public updateOption() { ...

Error encountered during Next.js build process: 'workerError'

I encountered this error while trying to build a Next.js app in production using 'yarn build'. I am completely lost and unable to find any helpful resources to resolve this. Please, I need assistance urgently!!! TypeError: Converting circular s ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...