Search code examples
javascriptiosreact-nativesettimeoutmixins

React Native timemixin cancel timer timeout


I found out how to cancel Javascript's timeout but how can I cancel a timer mixin? Timermixin is recommended for use with React Native over the Javascript timeout.

var TimerMixin = require('react-timer-mixin');

this.setTimeout(() => {this.setState({results: ' '})}, 1800)

I need to have it canceled if other actions are executed.


Solution

  • Solution

    var clearId = this.setTimeout(() => {this.setState({results: ' '})}, 1800);
    this.setState({ clearId: clearId});
    

    ...somewhere later when you want to cancel the setTimeout call

    this.clearTimeout(this.state.clearId)  
    

    Explanation

    You can cancel it the same way you would a regular setTimeout, by using clearTimeout. clearTimeout will prevent the function from running if it hasn't been called yet.

    When setTimeout is called, it "returns a number representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer." http://www.w3schools.com/jsref/met_win_settimeout.asp

    Since I imagine you'll want to call clearTimeout in a separate function, you can store the clearId as a state property so it can be easily referenced later in a separate function.

    If want to learn more about Timers in React Native, I found this documentation helpful https://facebook.github.io/react-native/docs/timers.html.

    Also

    By using the TimerMixin (instead of the regular setTimeout method), the setTimeout call will be prevented automatically if the component unmounts. Very useful! This is why you should make sure to use the TimerMixin instead of regular Timer methods.

    "We found out that the primary cause of fatals in apps created with React Native was due to timers firing after a component was unmounted." https://facebook.github.io/react-native/docs/timers.html

    The TimerMixin will avoid this and make sure all Timer calls are cleared when a component unmounts.