我正在使用Typescript在Angular 2中开发一个网站,我想知道是否有实现thread.sleep(ms)
功能的方法。
我的用例是在几秒钟后提交表单后重定向用户,这在html或javascript中很容易,但我不确定如何在Typescript中做到这一点。
非常感谢,
发布于 2016-06-11 14:17:16
这是可行的:(感谢评论)
setTimeout(() =>
{
this.router.navigate(['/']);
},
5000);
发布于 2018-06-11 12:09:32
由于某些原因,上述公认的答案在新版本的Angular (V6)中不起作用。
为此,请使用以下代码..
async delay(ms: number) {
await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}
上面的方法对我很有效。
用法:
this.delay(3000);
或者更准确的方式
this.delay(3000).then(any=>{
//your task after delay.
});
发布于 2018-10-31 11:24:33
使用RxJS
import { timer } from 'rxjs';
// ...
timer(your_delay_in_ms).subscribe(x => { your_action_code_here })
x
为0。
如果您向timer
提供第二个参数period
,则每隔period
毫秒将发出一个新数字(x =0则x= 1,x= 2,...)。
有关更多详细信息,请参阅official doc。
https://stackoverflow.com/questions/37764665
复制相似问题