clearInterval清除定时器失效的原因

在本页面定义了一个定时器,离开页面的时候清除定时器,发现失效。
原因是在本页面的不同地方调用了这个定时器,最后清除的只是最后一次调用的定时器,之前的定时器都没有清除。

比如,我定义了一个定时器

getTimer(){
     

       this.timer = setInterval(() => {
     

           console.log('定时器')

       }, 2000)

}

在刚进入页面的时候调用了一次

componentDidMount() {
     

	this.getTimer()
}

然后,在app处于active状态的时候又调用了一次

_handleAppStateChange = (nextAppState) => {
     

        if (nextAppState=='active' ) {
     

            this.getTimer();
            
        }

        this.setState({
     appState: nextAppState});
}

如果,停留在本页面的时候触发了_handleAppStateChange(),也就是二次调用的this.getTimer()
这样在卸载页面的时候使用clearInterval清除定时器,清除的只是_handleAppStateChange()方法里的定时器,并没有清除componentDidMount()里的定时器。

那么,我们应该怎么把所有的定时器都清除掉呢。
我的做法是,第一次正常调用定时器,第二次以以后的每一次调用定时器之前都将原来的定时器清除掉就可以了。

代码就可以写成
第一次正常调用

componentDidMount() {
     

	this.getTimer()
}

第二次在调用定时器之前,将原来的定时器用clearInterval清除掉就好了

_handleAppStateChange = (nextAppState) => {
     

        if (nextAppState=='active' ) {
     
        
			this.timer&&clearInterval(this.timer);
            this.getTimer();
            
        }

        this.setState({
     appState: nextAppState});
}

那么,在卸载本页面的时候,再清除一次定时器,所有的定时器都会被关闭掉。

async componentWillUnmount() {
     
        console.log('卸载')
        this.timer&&clearInterval(this.timer);
}

若有疑问,可留言!
如有帮助,可给请作者的一杯咖啡添砖加瓦:

在这里插入图片描述

你可能感兴趣的:(JavaScript)