forked from ryckman1/ui-waitlist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.js
62 lines (51 loc) · 1.55 KB
/
Timer.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import React from 'react';
import moment from 'moment';
const TICK_INTERVAL = 1000;
const PAUSED = "paused";
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
startDate: props.startDate,
timerState: props.timerState
};
}
/** react life-cycle */
componentDidMount() {
this.timerId = setInterval(() => this.tick(), TICK_INTERVAL);
}
componentWillReceiveProps(nextProps) {
this.setState({
startDate: nextProps.startDate,
timerState: nextProps.timerState
});
}
componentWillUnmount() {
clearInterval(this.timerId);
}
/** tick-tock */
tick() {
const timerState = this.state.timerState;
if(timerState && timerState !== PAUSED) {
this.setState({ now: moment() });
}
}
formatTime(millis) {
const mins = ~~(millis / 1000 / 60);
const secs = ~~(millis / 1000) - mins * 60;
return `${(mins < 10 ? '0' : '') + mins}m ${(secs < 10 ? '0' : '') + secs}s`;
}
getDispTime() {
const now = moment();
const start = this.state.startDate;
const totalTime = this.props.totalTime;
let remaining = totalTime - now.diff(start);
remaining = remaining < 0 ? 0 : remaining;
remaining = remaining > totalTime ? totalTime : remaining;
return <div>{this.formatTime(remaining)}</div>;
}
render() {
return <div>{this.getDispTime()}</div>;
}
}
export default Timer;