[angular] Typescript sleep

I'm developing a website in Angular 2 using Typescript and I was wondering if there was a way to implement thread.sleep(ms) functionality.

My use case is to redirect the users after submitting a form after a few seconds which is very easy in html or javascript but I'm not sure how to do it in Typescript.

Many thanks,

This question is related to angular typescript

The answer is


If you are using angular5 and above, please include the below method in your ts file.

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

then call this delay() method wherever you want.

e.g:

validateInputValues() {
    if (null == this.id|| this.id== "") {
        this.messageService.add(
            {severity: 'error', summary: 'ID is Required.'});
        this.delay(3000).then(any => {
            this.messageService.clear();
        });
    }
}

This will disappear message growl after 3 seconds.


For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

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

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

import { timer } from 'rxjs';

await timer(1000).pipe(take(1)).toPromise();

this works better for me


This works: (thanks to the comments)

setTimeout(() => 
{
    this.router.navigate(['/']);
},
5000);

With RxJS:

import { timer } from 'rxjs';

// ...

timer(your_delay_in_ms).subscribe(x => { your_action_code_here })

x is 0.

If you give a second argument period to timer, a new number will be emitted each period milliseconds (x = 0 then x = 1, x = 2, ...).

See the official doc for more details.


Or rather than to declare a function, simply:

setTimeout(() => {
    console.log('hello');
}, 1000);

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?