-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.jsx
48 lines (40 loc) · 1.19 KB
/
timer.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React from 'react';
export default class CountdownTimer extends React.Component {
constructor() {
super();
this.state = { time: {}, seconds: 120};
this.timer = 0;
this.countDown = this.countDown.bind(this);
}
//start timer once refresh the page
componentDidMount() {
this.countDown();
this.setState({ time: this.convert(this.state.seconds)});
if (this.timer === 0) {
this.timer = setInterval(this.countDown, 1000);
}
}
convert(second){
let minutes = Math.floor(second % (60 * 60) / 60);
let seconds = Math.floor(second % (60 * 60) % 60);
return {"minute": minutes, "second": seconds};
}
countDown() {
let seconds = this.state.seconds - 1;
this.setState({time: this.convert(this.state.seconds), seconds: seconds});
if (seconds === 0) {
clearInterval(this.timer);
}
}
renderText(){
return "Time out. You lost.";
}
render() {
return(
<div className="time">
Time Left: {this.state.time.minute}m {this.state.time.second}s
<p>{this.state.seconds === 0?this.renderText() : ""}</p>
</div>
);
}
}