In my React Native app, I'm using setInterval
to poll an API call every few seconds to achieve a certain goal, like this:
this.timer = setInterval(() => this.doSomething(), 4000);
The problem is it only starts after 4 seconds. I have read other answers that suggest calling the function immediately and then calling setInterval
to execute it again after a delay, but that is not working for me because what if the first call succeeds in achieving what I needed it to do? Then I don't want it to be called again, only once would have been enough.
How do I call it once, then if it fails I start polling it every 4 seconds?
Edit: Forgot to mention specifically that this.doSomething
is an async function.
CodePudding user response:
Execute the function first and then setInterval if it fails. You just need to return from the function whether it succeeded, and add an if statement before using setInterval.
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);
}
Async version:
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);
}
}
)