hichem belfekih
hichem belfekih

Reputation: 115

CountDown Timer with start/Pause and reset button

i want to create a countDown timer in React JS with the "start","Pause" and "Reset" Button in order to Manipulate the timer. As a beginner developper in React and JS, i create a state variable "secondsElapsed" in order to enter the time in seconds for the timer.

The "startTime" function is to start the countdown for the timer in each second. The "resetTime" function is to reset the "secondsElapsed" to 0. The "pauseTime" function is to pause the timer.

The other functions are to calculate the time and returned it in specific field.

Here the description image

Discriptive Timer

The countdown is functionnal after clicking on the "Start Button " and seconds are decreasing. The problem is that the minutes and hours fields are not decreasing as supposed to be each minute and each hour.

Here my codesandbox link: https://codesandbox.io/s/y3l1ymq6r1

Here my React Js code:

import React from "react";

export default class Timer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      secondsElapsed: 122 //time in seconds
    };
  }

  getHours() {
    return ("0" + Math.round(this.state.secondsElapsed / 3600)).slice(-2);
  }

  getMinutes() {
    return ("0" + Math.round((this.state.secondsElapsed % 3600) / 60)).slice(
      -2
    );
  }

  getSeconds() {
    return ("0" + (this.state.secondsElapsed % 60)).slice(-2);
  }

  startTime() {
    var _this = this;
    this.countdown = setInterval(function() {
      _this.setState({ secondsElapsed: _this.state.secondsElapsed - 1 });
    }, 1000);
  }

  resetTime() {
    this.reset = this.setState({
      secondsElapsed: (this.state.secondsElapsed = 0)
    });
  }

  pauseTime() {
    clearInterval(this.countdown);
  }

  render() {
    return (
      <div className="App">
        <h1>
          {this.getHours()}:{this.getMinutes()}:{this.getSeconds()}
        </h1>
        <button onClick={() => this.startTime()}>Start</button>
        <button onClick={() => this.pauseTime()}>Pause</button>
        <button onClick={() => this.resetTime()}>Reset</button>
      </div>
    );
  }
}

Upvotes: 2

Views: 3464

Answers (1)

Okeano
Okeano

Reputation: 136

I would work with Math.floor() for this case you have to count up and not downwards.

Timer:

_this.setState({ secondsElapsed: _this.state.secondsElapsed + 1 });

For the minutes:

return ("0" + Math.floor((this.state.secondsElapsed % 3600) / 60)).slice(-2);

For the hours:

return ("0" + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);

Upvotes: 1

Related Questions