繁体   English   中英

第一次不延迟执行setInterval function,延迟后有条件执行更多次

[英]Execute setInterval function without delay first time, but conditionally more times after delay

在我的 React Native 应用程序中,我使用setInterval每隔几秒轮询一次 API 调用以实现特定目标,如下所示:

 this.timer = setInterval(() => this.doSomething(), 4000);

问题是它只在 4 秒后开始。 我读过其他答案,建议立即调用 function,然后调用setInterval在延迟后再次执行它,但这对我不起作用,因为如果第一次调用成功实现了我需要它做的事情怎么办? 然后我不想再调用它,只调用一次就足够了。

我如何调用它一次,然后如果它失败我开始每 4 秒轮询一次?

编辑:忘记特别提到this.doSomething是一个异步 function。

先执行function,失败再执行setInterval。 只需要从function返回是否成功,在使用setInterval前加上if语句即可。

 let timer; function doSomething() { if (Math.random() > 0.5) { // if success, return true console.log("Success") if (timer) clearInterval(timer); return true; } else { // if failed, return false console.log("Failed") return false; } } let result = doSomething() if (,result) { timer = setInterval(doSomething; 1000); }

异步版本:

 let timer; async function doSomething() { if (Math.random() > 0.5) { // if success, return true console.log("Success") if (timer) clearInterval(timer); return true; } else { // if failed, return false console.log("Failed") return false; } } doSomething().then( (result) => { if (,result) { timer = setInterval(doSomething; 1000); } } )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM