0

I am trying to create an automatic counter in react which stops at 60. Here is my code:

import React, { Component } from "react";

class Profile extends Component {
  constructor(props) {
    super(props);

    this.state = { seconds: 0 };
  }
  tick() {
    if (this.state.seconds < 60) {
      this.setState(prevState => ({
        seconds: prevState.seconds + 1
      }));
    }
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 100);
  }

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

  render() {
    return <div>Seconds: {this.state.seconds}</div>;
  }
}

export default Profile;

It stops at 60 but I am worried that the component will continue to ask for the tick function again and again. I am not sure if it is the best practice or if there is a better way to do that. Thank you for your help.

1
  • 1
    just a thing: 100ms !== 1 second. Not sure if it's on purpose Commented Aug 13, 2018 at 10:50

2 Answers 2

2

It's OK to handle the interval inside the react component life circle. The only problem is that the tick will be called continuously after 60 in your case. You should clear the interval immediately after it finishes:

if (this.state.seconds < 60) {
  this.setState(prevState => ({
    seconds: prevState.seconds + 1
  }));
} else {
  clearInterval(this.interval);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are correct. Your component will never unmount in order to clear the interval. I would approach the problem differently.

You could use setTimeout. You set a timeout for every second. The callback will be a function that increases the number of seconds every time and reschedules the timeout, if the condition allows.

This way, you have a tick every second and you don't have to worry about the cleanup, because you simply no longer reschedule the timeout when you are done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.