176

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,

Antikhippe
  • 5,395
  • 2
  • 22
  • 38
kha
  • 16,333
  • 9
  • 28
  • 57
  • 9
    Typescript is a superset of JavaScript. So write it in JavaScript, and there you go: you have a TypeScript solution. – JB Nizet Jun 11 '16 at 14:09
  • This has got simpler since this question was originally answered. See https://stackoverflow.com/a/39914235/328817 – Sam Apr 21 '21 at 09:00

7 Answers7

277

You have to wait for TypeScript 2.0 with async/await for ES5 support as it now supported only for TS to ES6 compilation.

You would be able to create delay function with async:

function delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
}

And call it

await delay(300);

Please note, that you can use await only inside async function.

If you can't (let's say you are building nodejs application), just place your code in the anonymous async function. Here is an example:

    (async () => { 
        // Do something before delay
        console.log('before delay')

        await delay(1000);

        // Do something after
        console.log('after delay')
    })();

Example TS Application: https://github.com/v-andrew/ts-template

In OLD JS you have to use

setTimeout(YourFunctionName, Milliseconds);

or

setTimeout( () => { /*Your Code*/ }, Milliseconds );

However with every major browser supporting async/await it less useful.

Update: TypeScript 2.1 is here with async/await.

Just do not forget that you need Promise implementation when you compile to ES5, where Promise is not natively available.

PS

You have to export the function if you want to use it outside of the original file.

v-andrew
  • 14,404
  • 5
  • 32
  • 38
  • 1
    **Update**: _async/await and generators support for ES5/ES3_ was moved to TypeScript 2.1 – v-andrew Jul 26 '16 at 17:09
  • 8
    event without await, you can do delay(20000).then(()=>{ – ZZZ Dec 17 '16 at 11:00
  • 1
    for some reason this didn't work for me `await new Promise(resolve => setTimeout(resolve, 1000)).then(()=>console.log("fired"));` but this worked `await new Promise(resolve => setTimeout(()=>resolve(), 1000)).then(()=>console.log("fired"));` – fjch1997 Mar 12 '18 at 20:57
  • @fjch1997, wrap it in `async` function. I added example – v-andrew Sep 22 '18 at 17:33
  • 2
    The declaration of 'delay' function does not need async keyword, as it already returns a promise. – SlavaSt Mar 05 '19 at 13:11
  • @SlavaSt True. It wasn't there but someone convinced me to add it. Removing. – v-andrew Mar 05 '19 at 20:29
  • This worked great. Just FYI, Resharper will flag Promise as being in an inaccessible module, but it works. Just do a // ReSharper disable TsResolvedFromInaccessibleModule – stevejoy32 Mar 09 '19 at 00:18
  • in short for typescript: `const delay = (ms: number) => new Promise(r => setTimeout(r, ms));` and use it like `await delay(5000)` – cyptus Oct 28 '19 at 21:14
117

This works: (thanks to the comments)

setTimeout(() => 
{
    this.router.navigate(['/']);
},
5000);
kha
  • 16,333
  • 9
  • 28
  • 57
  • 2
    I guess this one should be the accepted answer by now for the sake of simplicity. – Stefan Falk Sep 22 '18 at 20:12
  • 2
    @StefanFalk Hi Stefan. I accepted the other answer because it included this answer and also had other, more "typescripty" ways of doing the delay which may be of interest to others. I'm personally using this one throughout my code since I don't see any benefit in using async/await for this specific task but I'm not a TS purist and I go with whatever's easier/more readable, so I agree with you in principle :). – kha Oct 23 '18 at 06:34
  • 1
    I bumped it. Clean and effective. – Travis L. Riffle Sep 30 '20 at 09:01
32

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.
});
MarmiK
  • 5,320
  • 6
  • 34
  • 44
21

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.

Qortex
  • 5,389
  • 2
  • 30
  • 55
7

Or rather than to declare a function, simply:

setTimeout(() => {
    console.log('hello');
}, 1000);
Homer
  • 27
  • 10
Gebus
  • 191
  • 2
  • 3
6
import { timer } from 'rxjs';

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

this works better for me

Yohan Dahmani
  • 902
  • 12
  • 21
FabioLux
  • 529
  • 6
  • 14
2

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.

Jag
  • 79
  • 7