Skip to content

Commit

Permalink
feat: use setTimeout rather than setInterval to avoid drifting
Browse files Browse the repository at this point in the history
  • Loading branch information
troch committed Nov 28, 2015
1 parent 9bdcee1 commit 8da189e
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions modules/timer.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
import React, { Component, PropTypes, createElement } from 'react';
import React from 'react';

function timer(delay) {
return function TimerHoc(TimedComponent) {
class Timer extends Component {
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { tick: 0 };
this.setInterval = ::this.setInterval;
this.setTimeout = ::this.setTimeout;
this.stop = ::this.stop;
}

setInterval() {
this.timer = setInterval(() => {
setTimeout() {
const duration = delay - (this.startTime - Date.now()) % delay;
this.timer = setTimeout(() => {
this.setState({ tick: this.state.tick + 1 });
this.setTimeout();
}, delay);
}

stop() {
clearInterval(this.timer);
clearTimeout(this.timer);
}

componentDidMount() {
this.setInterval();
this.startTime = Date.now();
this.setTimeout();
}

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

return createElement(TimedComponent, { ...props, tick, delay, stop });
return React.createElement(TimedComponent, { ...props, tick, delay, stop });
}
};

Expand Down

0 comments on commit 8da189e

Please sign in to comment.