我正在尝试在 Angular 2 环境中管理计时器,而 clearTimeout 似乎只能在大约一半的时间内正常工作。我正在用 TypeScript 编写。
我将计时器保留在它自己的服务中:
export class TimeoutService {
constructor(
private router: Router,
private httpService: HttpService
) {}
//Properties
private timer;
//Methods
public clearTimer() {
clearTimeout(this.timer);
}
private logOut() {
return this.httpService.Post('api/session/logout', '');
}
private redirectToTimeoutPage() {
this.router.navigate(['/timeout']);
}
public refreshTimer() {
console.log('refreshing timer');
if (this.timer) {
this.clearTimer();
this.setTimer();
}
}
public startTimer() {
this.setTimer();
}
private setTimer() {
this.timer = setTimeout(() => {
this.logOut()
.then(() => {
this.clearTimer();
this.redirectToTimeoutPage();
});
}, 30000);
}
}
我从 refreshTimer 方法中的 console.log 知道它在我期望的时候被调用,而不是在其他情况下。然而,大多数情况下,较早的计时器不会被 clearTimeout 调用取消,并且会在三十秒结束后触发,即使它们本应被新计时器替换。
我已经解决了关于此的其他 SO 问题,据我所知,没有一个适用于我的情况。
我得到的一个线索,但我无法破译,如果我在 refreshTimer 中删除对 this.setTimer()
的调用,那么 clearTimeout 调用似乎工作正常。换句话说,创建一个新计时器会以某种方式导致旧计时器存活下来。我在这里缺少什么?
谢谢!
最佳答案
在 refreshTimer
中,您需要在调用 this.setTimer()
之前调用 this.clearTimer()
。
但是,在 startTimer
中,您不会调用 this.clearTimer()
。因此,如果调用代码多次调用 startTimer
而没有执行任何调用 this.clearTimer
的操作,您将启动多个超时,但只有当再次调用 this.clearTimer
时,最后一个将被您的类(class)记住并取消。
关于javascript - clearTimeout 偶尔失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451507/