Skip to content

Commit 0a30f08

Browse files
committed
refactor stopwatch. allow classname and starttime. remove radium and moment
1 parent d054530 commit 0a30f08

File tree

1 file changed

+38
-18
lines changed

1 file changed

+38
-18
lines changed

src/timers/Stopwatch.js

+38-18
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,71 @@
11
import React from 'react';
2-
import Radium from 'radium';
3-
import moment from 'moment-timezone';
42
import { sprintf } from 'sprintf-js/src/sprintf';
53

64
export class Stopwatch extends React.Component {
5+
76
static propTypes = {
87
style: React.PropTypes.object,
9-
}
8+
className: React.PropTypes.string,
9+
start: React.PropTypes.instanceOf(Date),
10+
};
1011

1112
static defaultProps = {
1213
style: {},
13-
}
14+
};
15+
16+
state = {
17+
elapsed: 0,
18+
startTime: new Date(),
19+
timer: null,
20+
};
1421

1522
componentWillMount() {
23+
const startTime = this.props.start || new Date();
1624
this.setState({
17-
elapsed: 0,
18-
startTime: moment(),
25+
elapsed: this.calculateElapsedSeconds(startTime),
26+
startTime: startTime,
1927
timer: setInterval(() => {
2028
this.setState({
21-
elapsed: moment.duration(
22-
moment().diff(this.state.startTime)
23-
).asSeconds(),
29+
elapsed: this.calculateElapsedSeconds(this.state.startTime),
2430
});
2531
}, 500),
2632
});
2733
}
34+
35+
calculateElapsedSeconds = (startTime) => {
36+
const now = new Date();
37+
const timeDiff = now.getTime() - startTime.getTime();
38+
39+
return Math.abs(timeDiff / 1000);
40+
};
41+
2842
componentWillUnmount() {
2943
clearInterval(this.state.timer);
3044
}
3145

32-
getDiffString = () => {
33-
const duration = moment.duration(this.state.elapsed, 'seconds');
46+
getTimeDiffString = () => {
47+
const seconds = Math.floor(this.state.elapsed % 60);
48+
const minutes = Math.floor(this.state.elapsed / 60) % 60;
49+
const hours = Math.floor(this.state.elapsed / 3600);
50+
51+
let timeString = '';
3452

35-
if (duration.hours() > 0) {
36-
return duration.hours() + ':' + sprintf('%02d', duration.minutes()) + ':' + sprintf('%02d', duration.seconds());
53+
if(hours > 0) {
54+
timeString += sprintf('%02d', hours) + ':';
3755
}
3856

39-
return duration.minutes() + ':' + sprintf('%02d', duration.seconds());
40-
}
57+
timeString += sprintf('%02d', minutes) + ':' + sprintf('%02d', seconds);
58+
59+
return timeString;
60+
};
4161

4262
render() {
4363
return (
44-
<span style={this.props.style}>
45-
{this.getDiffString()}
64+
<span style={this.props.style} className={this.props.className}>
65+
{this.getTimeDiffString()}
4666
</span>
4767
);
4868
}
4969
}
5070

51-
export default Radium(Stopwatch);
71+
export default Stopwatch;

0 commit comments

Comments
 (0)