clearTimeout fails sporadically
我正在尝试在Angular 2环境中管理计时器,而clearTimeout似乎只能正常工作大约一半的时间。 我正在用TypeScript编写。
我将计时器保留在自己的服务中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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调用取消,并且会在三十秒结束后立即触发,即使它们应该已被新的计时器替换。
我已经解决了其他有关此的问题,据我所知,没有一个问题适用于我的情况。
我无法理解的一个提示是,如果我在refreshTimer中删除了对
谢谢!
在
但是,在
在
1 2 3 4 | public clearTimer() { clearTimeout(this.timer); this.timer = null; // <-- You also want your variable to become null here. } |
然后,在调用
同样(FYI),正如我在评论中说的那样,这是初始化所有变量的一种很好的最佳实践,这样就不会出现"意外"值。
1 | private timer; |
应该:
1 | private timer = null; |
我会将对