JavaScript Stop an interval from another function in React stop interval in javascript,stop interval in js,stop interval

I am new to React and I try to build a timer component. Now I have the start function working but I would also like to stop the timer by an onclick handler. The problem is that the start function uses an interval, but I don't know how to stop that interval from another function.

My JS code

  constructor() {
    super();

    this.state = {
      times: [],
      timer: false,
      currentTimer: 0
    }

    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);

  }

  startTimer() {

    const start = Date.now();

    this.setState({ timer: true });

    var timer = setInterval(() => {

      let time = new Date() - start;

      this.setState({ currentTimer: Math.round(time / 1000)});


    }, 1000);

  }

  stopTimer() {

    this.setState({ timer: false });
    console.log('stopped');

    //Clear interval here

  }

I know that the timer variable is the identifier of that interval but how can I access it and then stop it? I have tried almost everything but nothing seems to work and I just don't know how I can fix that.

Answer:1

To stop the timer, you need the timer id, So First job will be to store the id in such a way that it should be accessible in all the class methods. Second job will be use clearInterval to clear the timer (timer id will be required here).

One option is, Store the timer id in class instance.

Like this:

startTimer() {
    const start = Date.now();
    this.setState({ timer: true });
    // storing the id
    this.timerID = setInterval(() => {
        let time = new Date() - start;
        this.setState({ currentTimer: Math.round(time / 1000)});
    }, 1000);
}

stopTimer() {
    this.setState({ timer: false });
    clearInterval(this.timerID);
}

Working code:

class App extends React.Component {

  constructor(){
     super();
     this.state = {currentTimer: ''}
     this.startTimer = this.startTimer.bind(this);
     this.stopTimer = this.stopTimer.bind(this);
  }
  
  startTimer() {
    const start = Date.now();
    this.timerID = setInterval(() => {
        let time = Math.random() * 10;
        this.setState({ currentTimer: time});
    }, 1000);
  }

  stopTimer() {
     clearInterval(this.timerID);
  }
  
  render(){
     return (
        <div>
          Value: {this.state.currentTimer || '0'}
          <br />
          <button onClick={this.startTimer}>Start timer</button>
          <button onClick={this.stopTimer}>Stop timer</button>
        </div>
     )
  }

}

ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app' />
Answer:2

Save the timerId as a class instance variable which can then be accessed from other functions and used to clear the interval

constructor() {
    super();

    this.state = {
      times: [],
      timer: false,
      currentTimer: 0
    }
    this.timer = null;

    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);

  }

  startTimer() {

    const start = Date.now();

    this.setState({ timer: true });

    this.timer = setInterval(() => {

      let time = new Date() - start;

      this.setState({ currentTimer: Math.round(time / 1000)});


    }, 1000);

  }

  stopTimer() {

    this.setState({ timer: false });
    console.log('stopped');

    //Clear interval here
    clearInterval(this.timer)
  }
Answer:3

I have an issue with tooltip in Highcharts column charts. When series fill my chart, the tooltip is under the serie. But he is cut by then end of div, as you can see here : What should I do to make ...

I have an issue with tooltip in Highcharts column charts. When series fill my chart, the tooltip is under the serie. But he is cut by then end of div, as you can see here : What should I do to make ...

  1. dynamic position tooltip javascript
  2. dynamic position tooltip jquery
  3. dynamic position tooltip
  4. css dynamic tooltip position

I need to take a JSON object and get the titles console logged for an auto complete feature. AN example of what my json looks like is below: [ { "title": "Example 1", "url": "http:\/\/www....

I need to take a JSON object and get the titles console logged for an auto complete feature. AN example of what my json looks like is below: [ { "title": "Example 1", "url": "http:\/\/www....

  1. json parsing error redshift
  2. json parsing error 8001
  3. json parsing error in row starting at position
  4. json parsing error no value for
  5. json parsing error android
  6. json parsing error
  7. json_parsing_error unexpected character (t) at position 0
  8. json_parsing_error unexpected character (-) at position 0
  9. json parsing error value
  10. json parsing error python
  11. json parsing error paladins
  12. json_parsing_error unexpected token end of file at position
  13. json parsing error unexpected token expected
  14. json_parsing_error unexpected token end of file
  15. json parsing error unexpected token
  16. json parsing error fcm
  17. json parse error unexpected eof
  18. json parse error cannot construct instance of
  19. json parse error cannot deserialize instance of
  20. json parse error unexpected identifier object

My code resembles this: router.post("/", (req, res, next) => { foo() .then((result) => { res.send(result) }) .catch((error) => { cosnole.log(error) }) //I only want the bar() ...

My code resembles this: router.post("/", (req, res, next) => { foo() .then((result) => { res.send(result) }) .catch((error) => { cosnole.log(error) }) //I only want the bar() ...

I'm looking for maven config to minify js/css files for a spring boot application. For a normal java web app the following config works <plugins> <plugin> ...

I'm looking for maven config to minify js/css files for a spring boot application. For a normal java web app the following config works <plugins> <plugin> ...

  1. spring boot minify javascript
  2. spring boot minify html
  3. spring boot minify css
  4. spring boot minify
  5. spring boot minify-maven-plugin
  6. spring boot minification
  7. spring boot thymeleaf minify
  8. spring boot json minify
  9. spring boot maven minify