-
Notifications
You must be signed in to change notification settings - Fork 100
/
Interval.js
67 lines (55 loc) · 1.23 KB
/
Interval.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { Component } from 'react'
import renderProps from '../utils/renderProps'
class Interval extends Component {
state = {
times: 0,
}
intervalId = undefined
_clearIntervalIfNecessary = () => {
if (this.intervalId) {
this.intervalId = clearInterval(this.intervalId)
}
}
_setIntervalIfNecessary = delay => {
if (Number.isFinite(delay)) {
this._clearIntervalIfNecessary()
this.intervalId = setInterval(
() => this.setState(s => ({ times: s.times + 1 })),
delay
)
}
}
stop = () => {
this._clearIntervalIfNecessary()
}
start = delay => {
const _delay =
typeof delay === 'number'
? delay
: this.props.delay != null ? this.props.delay : 1000
this._setIntervalIfNecessary(_delay)
}
toggle = () => {
this.intervalId ? this.stop() : this.start()
}
componentDidMount() {
this.start()
}
componentDidUpdate(prevProps) {
if (prevProps.delay !== this.props.delay) {
this.stop()
this.start()
}
}
componentWillUnmount() {
this.stop()
}
render() {
return renderProps(this.props, {
start: this.start,
stop: this.stop,
toggle: this.toggle,
})
}
}
export default Interval