Typescript sleep

前端 未结 7 557
后悔当初
后悔当初 2020-11-30 20:02

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

相关标签:
7条回答
  • 2020-11-30 20:21

    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.

    0 讨论(0)
  • 2020-11-30 20:22

    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.
    });
    
    0 讨论(0)
  • 2020-11-30 20:25

    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.

    0 讨论(0)
  • 2020-11-30 20:27

    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.

    0 讨论(0)
  • 2020-11-30 20:30

    This works: (thanks to the comments)

    setTimeout(() => 
    {
        this.router.navigate(['/']);
    },
    5000);
    
    0 讨论(0)
  • 2020-11-30 20:32

    Or rather than to declare a function, simply:

    setTimeout(() => {
        console.log('hello');
    }, 1000);
    
    0 讨论(0)
提交回复
热议问题