Skip to content

Commit 8da189e

Browse files
committed
feat: use setTimeout rather than setInterval to avoid drifting
1 parent 9bdcee1 commit 8da189e

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

modules/timer.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,30 @@
1-
import React, { Component, PropTypes, createElement } from 'react';
1+
import React from 'react';
22

33
function timer(delay) {
44
return function TimerHoc(TimedComponent) {
5-
class Timer extends Component {
5+
class Timer extends React.Component {
66
constructor(props) {
77
super(props);
88
this.state = { tick: 0 };
9-
this.setInterval = ::this.setInterval;
9+
this.setTimeout = ::this.setTimeout;
1010
this.stop = ::this.stop;
1111
}
1212

13-
setInterval() {
14-
this.timer = setInterval(() => {
13+
setTimeout() {
14+
const duration = delay - (this.startTime - Date.now()) % delay;
15+
this.timer = setTimeout(() => {
1516
this.setState({ tick: this.state.tick + 1 });
17+
this.setTimeout();
1618
}, delay);
1719
}
1820

1921
stop() {
20-
clearInterval(this.timer);
22+
clearTimeout(this.timer);
2123
}
2224

2325
componentDidMount() {
24-
this.setInterval();
26+
this.startTime = Date.now();
27+
this.setTimeout();
2528
}
2629

2730
componentWillUnmout() {
@@ -32,7 +35,7 @@ function timer(delay) {
3235
const { props, stop } = this.props;
3336
const { tick } = this.state;
3437

35-
return createElement(TimedComponent, { ...props, tick, delay, stop });
38+
return React.createElement(TimedComponent, { ...props, tick, delay, stop });
3639
}
3740
};
3841

0 commit comments

Comments
 (0)