Using Delay or Sleep function in NativeScript/Angular for executing tasks asynchronously

My Sleep/Delay function is giving me trouble.

I attempted to utilize the delay function from 'rxjs/operators', but it seems to be failing.

Below is my code snippet:

sentence: string = "Hallo"

wordToMorse(sentence: any) {
        for (var char of sentence) {
            if (char != " ") {
                this.vibrateWord(char);
                this.pause(1000);

            } else {
                this.pause(1000);
            }

        }
    }

vibrateWord(character: any) {
        if (character == "H") {
            this.vibrator.vibrate(500);
        } else if (character == "a") {
            this.vibrator.vibrate(1000);
        } else if (character == "l") {
            this.vibrator.vibrate(500);
        } else if (character == "o") {
            this.vibrator.vibrate(2000);
        }
    }

async pause(ms: number) {
        await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
    }

I am anticipating that there should be a 1-second delay after each vibration for a letter in the sentence.

Answer №1

The position of the async await in your code needs to be adjusted, here is a revised version:

async wordToMorse(sentence: any) { // <------ Update
    for (var char of sentence) {
        if (char != " ") {
            this.vibrateWord(char);
            await this.delay(1000); // <------ Update

        } else {
            await this.delay(1000); // <------ Update
        }

    }
}

delay(ms: number) { // <------ Update
    return new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired")); // <------ Update
}

Answer №2

If you want to achieve this task in a neat manner, you can utilize Observables:

from(sentence.split('')).pipe(
      take(sentence.length),
      concatMap(letter => of(letter).pipe(delay(1000))),
      tap(letter => {
        // implement vibration logic here
      })
    ).subscribe();

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

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

Managing background tasks with Node.js in real-time

I am currently faced with the challenge of managing background events. When a user is temporarily banned, we save the ban expiration in our database to ensure they are unbanned at the right time. However, my current code checks every ban every 10 seconds ...

Having trouble updating state with useEffect in a React functional component

Currently, I am dealing with a React functional component that is calling an API to fetch data. The response from the API call is confirmed to be received successfully. My aim is to store this data in an array within the component's state so that it c ...

Issues with the Bootstrap Grid System not functioning correctly when inter-component communication is needed in Angular from parent to

This is the code from app.component.html file: <div class="container"> <div class="row" id="ads"> <div class="col-xs-4"> <app-card *ngFor="let car of cars" [carNotifyBadge]="car.carNotifyBadge" [ca ...

Can the output object from an angular form validator be obtained and utilized?

As per the documentation, The validator is capable of returning an object {[key: string]: any} or null This implies that it can return an object (for any) which includes detailed information about what went wrong during validation. For example: function ...

Issues Arising from Abstraction of Function to Service Layer in Angular Application

I have a filter function that takes in user filter selections and returns data accordingly. Currently, I am using this function in multiple components to avoid repetition (DRY). To streamline the process, I decided to refactor it into a service layer. Howe ...

Is Typescript reliable when working with a reference to a DOM element?

In this scenario, a function is provided with the task of obtaining a reference to a DOM element and executing certain actions: function getElementAndDoStuff() { // element: HTMLElement | null const element = document.getElementById('id'); ...

Looking to set multiple documents at once in AngularFire2 (firestore) similar to RealTime Database functionality?

Transitioning from Firebase's RealTime Database to Firestore has shown a difference in how data is added. Data Overview An object containing various products is at the core of my dataset. const productsObj { products : [ {...},{...},{...},{...} ...

Unit testing in Angular - creating mock services with observables

I'm currently facing an issue with my unit tests for a component that subscribes to an Observable from the service DataService in the ngOnInit() lifecycle hook. Despite my efforts, I keep encountering the error message TypeError: Cannot read propertie ...

Deploying a Spring Boot and Angular application

Looking for guidance in creating executable files with specific commands to run projects using Eclipse STS for Spring Boot applications and VS Code for Angular. Open to exploring other solutions as well. Struggling with the process of creating an executa ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

Using select2 in Angular 6: A step-by-step guide

Looking for guidance on incorporating "select2" with Angular 6 for autocomplete functionality. Any experienced users out there who can offer me assistance? Thanks in advance. ...

Dealing with Nodejs promises can be frustrating, especially when encountering errors, but incorporating the Sequelize ORM can

Currently I am working on developing a web application for nodejs using the popular sequelize ORM and typescript. Here is an example from my code: this.createNewGame(player.idPlayer).then((game) => { this.getBestScore(player.idPlayer).then((bestSc ...

Implementing cursor-based pagination in Next.js API Route with Prisma and leveraging the power of useSWRInfinite

I am working on implementing cursor-based pagination for a table of posts using Next.js API Route, Prisma, and useSWRInfinite. Currently, I am fetching the ten most recent posts with Prisma in a Next.js API Route and displaying them using useSWR, sorted b ...

An error occurred during runtime while attempting to resolve all parameters for the UserService

I recently started using Ionic and I am trying to set up a sidebar with a user profile header, displaying the user's details as seen in other similar apps depending on who is logged in. Unfortunately, I have come across the following error: Runtime ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

Do we need to manually transfer data between component data and form data when saving/loading from a web API?

When I submit data in my reactive form, the stored object is returned from the server. This can happen due to server logic altering a field that needs to be updated on the client side as well. onSave() { const data = this.form.value; console.log("savi ...

The issue with Cypress AzureAD login is that it consistently redirects users away from the intended Cypress window

Trying to incorporate the automation of Azure AD login using Cypress, I have been facing some challenges. Even after configuring the local session storage according to the instructions in this GitHub repository https://github.com/juunas11/AzureAdUiTestAu ...