我想寻求解决以下问题的方法:我有一款游戏,正在运行中,游戏会周期性的获取游戏的状态。如果用户注销,虽然游戏结束了。但问题是,游戏仍然在设定的时间间隔内发送放请求。
我正在寻找一个条件,例如如果put请求不成功或其他东西来清除间隔。
componentDidMount() {
let interval = setInterval(() => {
this.getGameInfo(this.props.match.params.id);
}, 2000);
if (this.getGameInfo(api get request) is unsuccessful(header not existent) { (pseudocode)
clearInterval(interval)
}
谢谢你
你可以从getGameInfo中返回一个承诺,然后在游戏中添加一个 .catch
回调函数来清除时间间隔
componentDidMount() {
let interval = setInterval(() => {
this.getGameInfo(this.props.match.params.id).catch(() => {
clearInterval(interval);
});
}, 2000);
}