Skip to content

Commit 4a74b33

Browse files
committed
rewrite and avoid setInterval for a cleaner implementation
1 parent 07f2d01 commit 4a74b33

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

modules/timer/index.js

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ type State = {
4141
}
4242

4343
export class Timer extends React.Component<Props, State> {
44-
_intervalId: ?IntervalID
4544
_timeoutId: ?TimeoutID
4645

4746
state = {
@@ -50,29 +49,25 @@ export class Timer extends React.Component<Props, State> {
5049
}
5150

5251
componentDidMount() {
53-
// get the time remaining until the next $interval
54-
let {interval} = this.props
55-
let nowMs = this.state.now.getTime()
56-
let untilNextInterval = interval - (nowMs % interval)
57-
58-
this._timeoutId = setTimeout(() => {
59-
this.updateTime()
60-
this._intervalId = setInterval(this.updateTime, this.props.interval)
61-
}, untilNextInterval)
52+
this.queue()
6253
}
6354

6455
componentWillUnmount() {
65-
if (this._timeoutId) {
66-
clearTimeout(this._timeoutId)
67-
}
56+
// eslint-disable-next-line no-eq-null
57+
this._timeoutId != null && clearTimeout(this._timeoutId)
58+
}
6859

69-
if (this._intervalId) {
70-
clearInterval(this._intervalId)
71-
}
60+
queue = () => {
61+
// get the time remaining until the next $interval
62+
let {interval} = this.props
63+
let nowMs = this.state.now.getTime()
64+
let untilNextInterval = msUntilIntervalRepeat(nowMs, interval)
65+
66+
this._timeoutId = setTimeout(this.updateTime, untilNextInterval)
7267
}
7368

7469
updateTime = () => {
75-
this.setState(() => ({now: new Date()}))
70+
this.setState(() => ({now: new Date()}), this.queue)
7671
}
7772

7873
refresh = async () => {

0 commit comments

Comments
 (0)