Search code examples
reactjssettimeout

stopping a timeout in reactjs?


Is there a way I can kill/(get rid of) a timeout in reactjs?

setTimeout(function() {
//do something
}.bind(this), 3000);

Upon some sort of click or action, I want to be able to completely stop and end the timeout. Is there a way to do this? thanks.


Solution

  • You should use mixins:

    // file: mixins/settimeout.js:
    
    var SetTimeoutMixin = {
        componentWillMount: function() {
            this.timeouts = [];
        },
        setTimeout: function() {
            this.timeouts.push(setTimeout.apply(null, arguments));
        },
    
        clearTimeouts: function() {
            this.timeouts.forEach(clearTimeout);
        },
    
        componentWillUnmount: function() {
            this.clearTimeouts();
        }
    };
    
    export default SetTimeoutMixin;
    

    ...and in your component:

    // sampleComponent.js:
    import SetTimeoutMixin from 'mixins/settimeout'; 
    
    var SampleComponent = React.createClass({
    
        //mixins:
        mixins: [SetTimeoutMixin],
    
        // sample usage
        componentWillReceiveProps: function(newProps) {
            if (newProps.myValue != this.props.myValue) {
                this.clearTimeouts();
                this.setTimeout(function(){ console.log('do something'); }, 2000);
            }
        },
    }
    
    export default SampleComponent;
    

    More info: https://facebook.github.io/react/docs/reusable-components.html