Skip to content

Commit 19a0e33

Browse files
committed
Merge branch 'master' of https://github.com/xendora/react-timer into readme-update-3
2 parents 435eddf + fec0b7d commit 19a0e33

File tree

2 files changed

+44
-26
lines changed

2 files changed

+44
-26
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ before_install:
1111
- echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
1212
- sudo apt-get update -qq
1313
- sudo apt-get install -y -qq yarn
14-
- yarn jest:all
1514
cache:
1615
yarn: true
1716
script:
17+
- yarn jest:all
1818
- yarn gh-pages-clean
1919
- yarn docz:deploy -u "${GITHUB_NAME} <${GITHUB_EMAIL}>" -m "Generated by Travis CI 🤖🤖🤖 - [Build#${TRAVIS_BUILD_NUMBER}]"

src/index.js

Lines changed: 43 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,52 @@
1-
import { useState, useEffect, useRef } from 'react';
1+
import { Component } from 'react';
22
import PropTypes from 'prop-types';
33

4-
const ReactTimer = ({
5-
children,
6-
start = 0,
7-
end = () => true,
8-
interval = 1000,
9-
onEnd = () => { },
10-
onTick = () => { },
11-
}) => {
12-
const [value, setValue] = useState(start);
13-
const timerRef = useRef();
4+
class ReactTimer extends Component {
5+
constructor(props) {
6+
super(props);
7+
this.state = {
8+
value: props.start || 0,
9+
};
10+
this.timer = null;
11+
}
1412

15-
useEffect(() => {
16-
if (!timerRef.current) {
17-
timerRef.current = setInterval(() => {
18-
setValue((val) => onTick(val));
19-
}, interval);
20-
}
21-
if (end(value)) {
22-
clearInterval(timerRef.current);
23-
onEnd(value);
13+
componentDidMount() {
14+
const {
15+
onTick,
16+
interval,
17+
end,
18+
onEnd,
19+
} = this.props;
20+
this.timer = setInterval(() => {
21+
this.setState(({ value }) => (
22+
{ value: onTick(value) }
23+
), () => {
24+
const { value: currentValue } = this.state;
25+
if (end(currentValue)) {
26+
clearInterval(this.timer);
27+
onEnd(currentValue);
28+
}
29+
});
30+
}, interval);
31+
}
32+
33+
componentWillUnmount() {
34+
if (this.timer) {
35+
clearInterval(this.timer);
2436
}
25-
}, [end, interval, onEnd, onTick, value]);
37+
}
2638

27-
useEffect(() => () => {
28-
clearInterval(timerRef.current);
29-
}, []);
39+
render() {
40+
const { children } = this.props;
41+
const { value } = this.state;
42+
return children(value);
43+
}
44+
}
3045

31-
return children(value);
46+
ReactTimer.defaultProps = {
47+
interval: 1000,
48+
onEnd: () => { },
49+
onTick: () => { },
3250
};
3351

3452
ReactTimer.propTypes = {

0 commit comments

Comments
 (0)