Originally, it was 25 + 5 clock on freeCodeCamp, but I changed it to countdown.

The countdown is simple: there is a default time on the page, click Start, and the second hand starts to rewind. When the second hand rewinds to 0, the minute hand rewinds to 1. Click Stop to stop the countdown.

When I got this problem, the initial difficulty was how to make the minute hand and hour hand move separately. Later, I came up with two states to represent them respectively.

The second difficulty is how to make the numbers move. There is a setInterval in JS that can be used to repeat functions, but at first I attached this function to render and it kept getting wrong, so I had to build a function before render.

In addition to where setInterval is placed, I’m also confused about how its gay friend clearInterval works. This function requires that it receive a stop signal, but I haven’t seen how it works on React before, so I googled it. One answer to stackFlow is to build signals inside functions. Tried to make the next, the result can!

The third difficulty is how to make the minute hand decrease and the hour hand return to 60 when the needle goes back to 0. I thought about it and decided to use conditional functions in the states. Because before using the state are directly assigned value, there is no condition, at the beginning also some nervous, try, unexpectedly can.

Once these three points are ok, basically there is no big problem. Of course there are some boundary values that are not perfect at all. I did this just to practice my thinking.

Post the source code:

class Clock extends React.Component{
  constructor(props){
    super(props)
    this.state={
      minute:60,
      second:60
    }
    this.start = this.start.bind(this)
    this.no = this.no.bind(this)
    this.end = this.end.bind(this)
  }

  start(){

    if(this.state.second>0){

      this.setState({
        minute:this.state.minute,
        second:this.state.second - 1
      }) 

    }

    else{

       this.setState({
        minute:this.state.minute - 1,
        second:this.state.second + 60
      }) 

    }

  }

  no(){
    this.id = setInterval(this.start,1000)
  }

  end(){
    clearInterval(this.id)
  }

  render(){
    return(
    <div>

    <div id="container">
      {this.state.minute} : {this.state.second}
    </div>

    <button onClick={this.no}>
      start
    </button>

    <button onClick={this.end}>
      end
    </button>

    </div>

  )}
}

ReactDOM.render(
  <Clock/>,
  document.getElementById("root")
)
Copy the code

 

CodePen demo