【发布时间】:2018-04-17 10:16:30
【问题描述】:
我一直在尝试通过 react-native 中的递归 setTimeout 来管理计时器。
但我面临的问题是,在某些设备中,计时器在处理过程中需要更多时间(例如 100-150 秒计时器中的 1-4 秒)。
我已经删除了 setInterval,因为它比递归 setTimeout 更糟糕。有什么想法可以让这个计时器变得完美吗?
编辑:主要问题是我在 2 个或更多设备上运行应用程序(在发布模式下)。计时器完美启动,但设备似乎有非常小的延迟,随着时间的推移而增加。
app中的api调用是并行完成的。
代码:
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)
}
【问题讨论】:
-
想到的是使用短间隔并检查
Date.now() -
时间永远无法保证。你到底想达到什么目的?
-
间隔之后你在叫什么?函数会不会太复杂以至于它们本身需要 1-4 秒才能执行,而不是 setTimeout / setInterval 不同步?
-
我正在做 api 调用,但我很清楚这可能需要几秒钟,所以我正在并行进行数据库调用(在我的情况下为 firebase),所以即使在调用失败或需要时间之后,它也不是影响定时器。 @Panosh
-
时机。是。绝不。保证。不在设备之间,不在一个设备内。您的代码需要期待这一事实并使用它。你的代码到底是什么,你想做什么?
标签: javascript react-native settimeout setinterval