Shashika Virajh
Shashika Virajh

Reputation: 9457

Start a countdown timer with react-natiev

I want to have a countdown component for my project. I tried by setting setInterval, but I have a requirement to pause and continue the timer. So How can I achieve this?

Upvotes: 0

Views: 528

Answers (1)

NiFi
NiFi

Reputation: 2458

I created a jsfiddle with a simple demonstration of how it can be done: https://jsfiddle.net/69z2wepo/258601/. Written using React but the principle is exactly the same with React Native.

class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      counter: 10,
    };

    this.interval = null;

    this.cleanUp = this.cleanUp.bind(this);
    this.decreaseCounter = this.decreaseCounter.bind(this);
    this.startCounter = this.startCounter.bind(this);
  }

  componentWillUnmount() {
    cleanUp();
  }

  cleanUp() {
    clearInterval(this.interval);
  }

  decreaseCounter() {
    if (this.state.counter === 0) {
        return this.cleanUp();
    }
    this.setState({counter: this.state.counter - 1});
  }

  startCounter() {
    this.interval = setInterval(this.decreaseCounter, 1000);
  }

  render() {
    return (
        <div>
        <button onClick={this.startCounter}>Start</button>
        Counter {this.state.counter}
        <button onClick={this.cleanUp}>Stop</button>
      </div>
    );
  }
}

Upvotes: 1

Related Questions