Delay the execution of a JavaScript method that resolves a promise

Currently, I am delving into the world of Angular 2, typescript, promises, and more. I've set up a small application for developer tools with a service that simply returns hard-coded data. This setup is purely for testing purposes.

I want to introduce a short delay in the service method to mimic server lag and test some of my controls effectively. However, I am struggling to find the correct syntax to achieve this. How can I insert a 5-second delay in my service call?

Developer Tools Service

@Injectable()
export class DeveloperService {
    getExampleData(): Promise<ExampleItem[]> {
        const examples: ExampleItem[] = [];
        examples.push({ id: 1, name: 'Spaceman Spiff', location: 'Outer Space', age: 12 });
        examples.push({ id: 2, name: 'Stupendous Man', location: 'The City', age: 30.5 });
        examples.push({ id: 3, name: 'Tracer Bullet', location: 'The City', age: 24 });
        examples.push({ id: 4, name: 'Napalm Man', location: 'War Zone', age: 43.333 });
        examples.push({ id: 5, name: 'Adult Calvin', location: 'In the future', age: 54 });

        // TODO: Add a delay here!
        return Promise.resolve(examples);
    }
}

Developer Tools App

getExampleData() {
    return (): Promise<Array<any>> => {
        return this.developerService.getExampleData();
    };
}

UPDATE: 1 I attempted to use setTimeout() within the control implementation call but faced issues with getting the data populated at that specific time. It would be ideal to incorporate the delay directly into the service call method to avoid having to add it repeatedly.

getExampleData() {
    setTimeout(() => (): Promise<Array<any>> => {
        return this.developerService.getExampleData();
    }, 5000);
}

Answer №1

Delayed promise using different libraries

Create a new promise that resolves with undefined

return new Promise(resolve =>
  setTimeout(resolve, 5000)
);

Create a new promise that resolves with a specific value

return new Promise(resolve => 
  setTimeout(() => resolve(value), 5000)
);

Extend an existing promise to add delay

return promise.then(value => 
  new Promise(resolve => 
    setTimeout(() => resolve(value), 5000)
  )
);

Utilizing Bluebird for delayed promises

The Bluebird promise library provides performance enhancements and useful features for delaying promise execution.

Create a new promise that resolves with undefined

return Bluebird.delay(5000);

Create a new promise that resolves with a specific value

return Bluebird.resolve(value).delay(5000);
// or
return Bluebird.delay(5000).return(value);

Delaying an existing Bluebird promise

return bluebirdPromise.delay(5000);

Delaying promises with RxJS

RxJS is commonly used in Angular projects and offers the ability to create or manipulate promises efficiently.

Create a new promise that resolves with undefined

return Observable.of().delay(5000).toPromise();
// or
return Observable.interval(5000).first().toPromise();

Create a new promise that resolves with a specific value

return Observable.of(value).delay(5000).toPromise();

Add delay to an existing promise using RxJS

return Observable.fromPromise(promise).delay(5000).toPromise();

Answer №2

Delaying Output Using RxJS 6

To delay the output in RxJs 6 by a specified number of milliseconds, you can utilize the code below.

Delaying with Default Value (emits 0)

return timer(n);

Delaying with a Custom Value

return of(value).pipe(delay(n));

or

return timer(n).pipe(mapTo(value));

Using a Promise to Delay

return from(promise).pipe(delay(n));

Converting to a Promise

Add .toPromise() after the pipe on any of the above examples.

return timer(n).toPromise();
return of(value).pipe(delay(n)).toPromise();

and so forth.

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

Is it possible to host both PHP and an Angular 4 CLI site on the same port?

I am currently working on developing a frontend web application in Angular 4 that will be connecting to an existing webservice. The goal is to eventually have both the frontend and backend sit within the same domain. I am using Visual Studio Code for front ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

Using TypeScript with React Router-dom

I am just starting to learn typeScript, and I have encountered a problem while trying to navigate from one functional component to another using History.push. Here is the approach I am attempting: history.push({ to: "some URL", state: {// some st ...

The operation of multiplying values is not functioning properly in the output field

I'm currently working on a functionality where an output field needs to multiply its value based on the input entered into another field. For example, if the input field is set to 2, then the output field should display the result of multiplying that ...

Having trouble with installing Bootstrap in Angular 5

My journey with Bootstrap began by executing the command below: npm install --save bootstrap The installation was a success, and I proceeded to incorporate the CSS as follows: "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", ...

Tips for choosing and unchoosing rows in angular 6

I am looking to extract the values from selected rows and store them in an array. However, I also need to remove a row from the result array when it is deselected. The issue with my current code is that every time I click on a row, the fileName values are ...

Troubleshooting overload errors within ReactJS: tips and tricks

import React from 'react' import { Link } from 'react-scroll' import "./Protocol.css" import { ANALYTICS, TRADE, USERS, TRADERS, VOTES, ZEROES } from "../../Constants" const Protocol = () => { return ( ...

What is the expected return type in TypeScript of a function that returns a void function?

I recently received feedback during a code review suggesting that I add return type values to my functions. However, I am unsure of what return type to assign to this particular function: function mysteryTypeFunction(): mysteryType { return function() ...

Accessing a data property within an Angular2 route, no matter how deeply nested the route may be, by utilizing ActivatedRoute

Several routes have been defined in the following manner: export const AppRoutes: Routes = [ {path: '', component: HomeComponent, data: {titleKey: 'homeTitle'}}, {path: 'signup', component: SignupComponent, data: {titleKe ...

What significance and intent does this assignment hold within the type declaration shown here?

Take a look at this code snippet: export type DataViewProps = { width: number, // in pixels height: number, // in pixels data: Data, }; export class DataView<P extends DataViewProps = DataViewProps> extends React.Component<P> { Can ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Angular2: Component View encountered an unexpected directive value of 'undefined'

My Angular2 Application requires me to showcase a list of questions that editors can generate. Each question can have 0 to n answers (options - such as 'yes', 'no', '5', etc.). To achieve this, I need to load the AnswerCompone ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

Updating events instantly with a single click in Angular 6: A step-by-step guide

Hello there, I am currently diving into learning Angular 6 and I have encountered a query. I want to achieve a functionality where upon clicking a button, the text on the button changes as well as the corresponding event that triggers when the button is cl ...

Is there a way to retrieve the date of the most recent occurrence of a specific "day" in TypeScript?

Looking to retrieve the date (in YYYY-MM-DD format) for the most recent "Wednesday", "Saturday", or any user-specified day. This date could be from either this week or last week, with the most recent occurrence of that particular day. For instance, if toda ...

The type 'Readonly<Ref<Readonly<any>>>' does not have the property 'forEach' available

Having an issue with state management in Vue3 (Pinia) using the Composition API. I successfully retrieved an array called countryCodes and now I want to copy all items from this array into another array called countries defined in the state. However, whe ...