kha*_*kha 93 typescript angular
我正在使用Typescript在Angular 2中开发一个网站,我想知道是否有办法实现thread.sleep(ms)功能.
我的用例是在几秒钟之后提交表单后重定向用户,这在html或javascript中非常容易,但我不知道如何在Typescript中执行此操作.
非常感谢,
v-a*_*rew 144
您必须等待具有async/ awaitfor ES5支持的TypeScript 2.0,因为它现在仅支持TS到ES6编译.
您可以使用以下命令创建延迟功能async:
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
Run Code Online (Sandbox Code Playgroud)
并称之为
await delay(300);
Run Code Online (Sandbox Code Playgroud)
请注意,您只能使用await内部async功能.
如果你不能(假设你正在构建nodejs应用程序),只需将代码放在匿名async函数中.这是一个例子:
(async () => {
// Do something before delay
console.log('before delay')
await delay(1000);
// Do something after
console.log('after delay')
})();
Run Code Online (Sandbox Code Playgroud)
在JS中你必须使用
setTimeout(YourFunctionName, Milliseconds);
Run Code Online (Sandbox Code Playgroud)
要么
setTimeout( () => { /*Your Code*/ }, Milliseconds );
Run Code Online (Sandbox Code Playgroud)
更新:TypeScript 2.1随附
async/await.
只是不要忘记Promise在编译到ES5时需要实现,其中Promise本身不可用.
kha*_*kha 71
这有效:(感谢评论)
setTimeout(() =>
{
this.router.navigate(['/']);
},
5000);
Run Code Online (Sandbox Code Playgroud)
Mar*_*miK 19
出于某种原因,上述接受的答案在新版本的Angular(V6)中不起作用.
为此使用此..
async delay(ms: number) {
await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}
Run Code Online (Sandbox Code Playgroud)
以上为我工作.
用法:
this.delay(3000);
Run Code Online (Sandbox Code Playgroud)
或更准确的方式
this.delay(3000).then(any=>{
//your task after delay.
});
Run Code Online (Sandbox Code Playgroud)
与RxJS:
const delay_observable = of('').pipe(delay( * your delay in ms * ));
delay_observable.subscribe(s => { *your action here* });
// Rest of the code continues to execute, your action will be done when time comes
Run Code Online (Sandbox Code Playgroud)
并且您需要正确包含RxJS指令。例如,在Angular中,您需要:
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
Run Code Online (Sandbox Code Playgroud)
小智 9
Or rather than to declare a function, simply:
setTimeout(() => {
console.log('hello');
}, 1000);
Run Code Online (Sandbox Code Playgroud)
ES6 中正确的做法是
import { setTimeout } from 'timers/promises';
await setTimeout(5000);
Run Code Online (Sandbox Code Playgroud)
现在它是本机节点方法。https://nodejs.org/api/timers.html
import { timer } from 'rxjs';
await timer(1000).pipe(take(1)).toPromise();
Run Code Online (Sandbox Code Playgroud)
这对我更有效
| 归档时间: |
|
| 查看次数: |
202976 次 |
| 最近记录: |