现在我在componentDidMount()方法中有这个:
setInterval(() => this.getTimeUntil(getTheTimeToAdd, count++), 1000);
它调用另一个方法来更新每秒倒计时。当用户倒计时应用程序可能关闭或iPhone进入休眠状态时,我遇到了问题。
我试图同时使用两者:
react-native-mauron85-background-geolocation
和
react-native-background-timer
即使在iPhone休眠时,为了保持倒计时,应用程序也会关闭。有什么建议吗?
答案 0 :(得分:1)
您可以做的是为每次调用创建新日期以查看已用时间。像
setInterval(function() {
Date d = new Date();
if (this.oldDate && this.oldDate.getTime() + DELAY_THRESHHOLD < d.getTime()) {
...
this.oldDate = d;
}
else {
... //should anything be here?
}
},500);
答案 1 :(得分:0)
由于您已经在使用react-native-background-timer
,
您可以使用setInterval
实例中的BackgroundTimer
。
假设您已正确链接项目,您应该可以
// In the constructor or the state
this.state = {
initialCounter: 120000, //Equivalents to 2 minutes
active: false, // To show or hide a label
}
componentWillMount() {
this.setIntervalId = BackgroundTimer.setInterval(() => {
if (this.state.initialCounter === 0) {
this.setState({
initialCounter: this.state.initialCounter,
active: true,
})
} else {
this.setState({
initialCounter: this.state.initialCounter - 1000,
active: false,
})
}
}, 1000)
}
// Make sure to unmount the listener when component unmounts
componentWillUnmount() {
BackgroundTimer.clearInterval(this.setIntervalId)
}
// Helper func to reinitiate the counter
_onUpdate = () => {
this.setState({ initialCounter: 120000, active: false })
}
// And inside your render you may display the timer by formatting with moment()
文档有点误导,因为setInterval
和clearInterval
也适用于IOS 。测试包 2.0.1
答案 2 :(得分:0)
尝试此代码,它应在每次应用程序唤醒时赶上。
const duration = 15; // duration in minute
const alertAt = Date.now() + duration * 60 * 1000;
const interval = setInterval(() => {
const remaining = alertAt - Date.now();
if (remaining < 0) {
// time is up
clearInterval(interval);
return;
}
console.log(remaining);
}, 10)