打字稿睡眠 [英] Typescript sleep

查看:81
本文介绍了打字稿睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typescript在Angular 2中开发一个网站,我想知道是否存在一种实现thread.sleep(ms)功能的方法.

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.

我的用例是在几秒钟后提交表单后重定向用户,这在html或javascript中非常容易,但是我不确定如何在Typescript中做到这一点.

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.

非常感谢,

推荐答案

您必须等待带有async/await的TypeScript 2.0才能获得ES5支持,因为它现在仅支持TS至ES6编译.

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

您将可以使用async创建延迟功能:

You would be able to create delay function with async:

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

并称呼它

await delay(300);

请注意,您只能在async函数中使用await.

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

如果不能(假设您正在构建nodejs应用程序),只需将代码放在匿名async函数中.这是一个示例:

If you can't (let's say you are building nodejs application), just place your code in 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')
    })();

TS应用程序示例: https://github.com/v-andrew/ts-template

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

在OLD JS中,您必须使用

setTimeout(YourFunctionName, Milliseconds);

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

但是,每一个支持async/await的主流浏览器都已过时.

However with every major browser supporting async/await it is obsolete.

更新: TypeScript 2.1在此处,带async/await.

Update: TypeScript 2.1 is here with async/await.

别忘了当您编译到ES5时(该Promise本身不可用),您需要Promise实现.

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

这篇关于打字稿睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆