/
index.js
46 lines (39 loc) · 1.05 KB
/
index.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
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
export default class Heartbeat extends Component {
constructor(props) {
super(props);
this.state = {
nextBeat: new Date().getTime() + this.props.heartbeatInterval,
timeout: null
};
}
componentDidMount() {
const nextBeat = new Date().getTime() + this.props.heartbeatInterval;
this.setState({
timeout: setTimeout(this.beat, nextBeat - new Date().getTime())
});
}
componentWillUnmount() {
clearTimeout(this.state.timeout);
}
beat = () => {
const nextBeat = this.state.nextBeat + this.props.heartbeatInterval;
const nextTimeout = setTimeout(this.beat, nextBeat - new Date().getTime());
this.setState({
nextBeat: nextBeat,
timeout: nextTimeout
});
this.props.heartbeatFunction();
};
render() {
return <Fragment />;
}
}
Heartbeat.propTypes = {
heartbeatInterval: PropTypes.number,
heartbeatFunction: PropTypes.func.isRequired
};
Heartbeat.defaultProps = {
heartbeatInterval: 1000
};