How to clearTimeout an async function when componentWillUnmount in a Reactjs component?

Cinque picture Cinque · Jul 12, 2017 · Viewed 10.2k times · Source

Here is the component:

class ChartComp extends Component{
    constructor(props){
        super(props);
        this.timer = null;
        this.loadData = this.loadData.bind(this);
    }

    componentWillMount(){
        this.loadData();
    }

    componentWillUnmount(){
        if(this.timer){
            clearTimeout(this.timer);
        }
    }

    loadData(){
        //...
        getJSON(url, msg=>{ //get data from server
            if(msg.success){
                //...
                this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
            }
        })
    }

    render(){
        //...
    }
}

The clearTimeout function will be called before the component is unmounted. But the timer is in an async function, and it starts again after I got response from server. So how can I make clearTimeout work?

Answer

SLaks picture SLaks · Jul 12, 2017

Set a flag in your class inside componentWillUnmount.

In your async callback, check whether that flag has been set, and, if so, stop immediately.