Skip to content

react-interval: enabled ignored when switched with callbackΒ #132

@antmarot

Description

@antmarot

Hi,

I used the component for a very simple task: count x seconds before stopping the interval.
Surprisingly, the interval never stopped.

Here a sample code

import ReactInterval from 'react-interval';

class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = { remaining: 5 };
    this.onTick = this.onTick.bind(this);
  }

  onTick() {
    const { remaining } = this.state;
    this.setState({ remaining: remaining - 1 });
  }

  render() {
    const { remaining } = this.state;
    return (
      <div>
        <ReactInterval
          enabled={remaining > 0}
          callback={this.onTick}
        />
        <span>{remaining}</span>
      </div>
    );
  }
}

export default Demo;

I found out that stop() was correctly called when enabled switched from true to false, but start() was then immediately called as well.

The issue is kind of related to the life-cycle of the component. For instance, if I use a setTimeout to delay the state change a bit, everything works. But if the enabled prop is switched to false "during" the callback, start() will be called anyway and the interval will not stop.

The culprit is probably this bit:

  callback = () => {
    if (this.timer) {
      this.props.callback();
      this.start();
    }
  };

It should be easily fixed by checking the enabled prop before calling start().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions