HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptangularCritical

How to implement sleep function in TypeScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthowfunctionsleepimplement

Problem

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 JavaScript but I'm not sure how to do it in TypeScript.

Solution

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(1000);


BTW, you can await on Promise directly:

await new Promise(f => setTimeout(f, 1000));


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 is 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.

Code Snippets

function delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
}
await delay(1000);
await new Promise(f => setTimeout(f, 1000));
(async () => { 
        // Do something before delay
        console.log('before delay')

        await delay(1000);

        // Do something after
        console.log('after delay')
    })();
setTimeout(YourFunctionName, Milliseconds);

Context

Stack Overflow Q#37764665, score: 581

Revisions (0)

No revisions yet.