I've been trying to manage a timer via recursive setTimeout in react-native.
But i'm facing the problem that in some devices the timer is taking some time more in process(like 1-4 seconds in around 100-150 seconds timer).
I've already removed setInterval as it was worse than recursive setTimeout. any ideas that how can i make this timer perfect?
Edit: the main problem is that i ran application(In release mode) in 2 or more devices. the timer starts perfectly but devices seem to have very small delay in them, which is quite increasing by time.
The api calls in app are done parrallely.
Code:
AnotherTimerHandler = () => {
this.time = setTimeout(() => {
if (this.state.gameState == timesup) {
console.log(timesup)
this.setState({ timer: this.state.timer - 1 });
if (this.state.timer <= 0) {
if (this.state.questionIndex < numberOfQuestions - 1) {
this.setState({ gameState: splash, timer: splashTime, QAndA: {}, correctAnswer: '', questionIndex: this.state.questionIndex + 1, answered: false })
} else {
// console.log('123')
clearInterval(this.time)
console.log(this.state.playerMode)
if (this.state.playerMode) {
const { username, firstName, lastName } = this.props.navigation.state.params.userData;
firebase.database().ref(`tblGame/${gameIdToLoad}/gameWinners`).push({ Email: firebase.auth().currentUser.email, Name: firstName + ' ' + lastName })
.then(() => this.props.navigation.navigate('Winner', { gameId: gameIdToLoad, prizeAmount: this.props.navigation.state.params.QuizData.prizeAmount }))
.catch(err => alert(err))
} else { this.props.navigation.navigate('Winner', { gameId: gameIdToLoad, prizeAmount: this.props.navigation.state.params.QuizData.prizeAmount }); }
}
}
}
else if (this.state.gameState == playing) {
console.log('playing')
if (this.state.timer == questionTimer) {
// console.log('playing1', this.state.timer)
// this.setState({ answerLoaded: false })
// this.QAndAHandler(Question)
this.refs.circularProgress.performLinearAnimation(0, (questionTimer - 1) * 1000)
}
this.setState({ timer: this.state.timer - 1 })
// if (this.state.timer == -1) {
if (this.state.timer <= 0) {
this.setState({ gameState: timesup, timer: answerTimer }); this.QAndAHandler(Ans);
// console.log('playing2', this.state.timer)
}
}
else if (this.state.gameState == splash) {
console.log(splash)
console.log(this.state.timer)
this.setState({ timer: this.state.timer - 1 })
if (this.state.timer == splashTime - 1) {
this.QAndAHandler(Question)
} else if (this.state.timer <= 0) this.setState({ timer: questionTimer, gameState: playing, answerLoaded: false })
}
// Dont call again if scren is being changed
return this.state.gameState == timesup && this.state.timer<=0 && !(this.state.questionIndex < numberOfQuestions - 1) ? null : this.AnotherTimerHandler()
}, 1000)
}