![](/img/trans.png)
[英]how to stop function from executing again until a certain time has passed
[英]How to wait until a function is true or some time has passed in angular 2
在角度2完全適合初學者,目前對此頗為困惑。
我有一個需要在另一個返回true或等待半秒后運行的函數。
private myFunction(details: Stuff) {
if (this.okToProceed(details))
{
this.doStuff(details);
}
}
如果不能繼續進行,我想在100毫秒內重試,但是如果我已經等待了500毫秒,那么無論如何我都想做東西。
我一直在弄亂setTimeout和setInterval,並試圖使okToProceed函數成為可觀察到的東西,但是我什么都沒得到。
進行一些遞歸(在超時之前遞歸直到okToProceed):
private myFunction(details: Stuff, i=0) {
if (i>=5 || this.okToProceed(details)) {
return this.doStuff(details);
}
setTimeout(this.myFunction.bind(this),100,i+1);
}
或使用一些花哨的ES7做真正酷的異步工作(無需遞歸檢查):
private async myFunction(details: Stuff) {
if (await this.okToProceed(details)) {
return this.doStuff(details);
}
}
okToProceed必須返回這樣的Promise:
okToProceed(details){
return Promise.resolve(true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.