-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-interval.js
More file actions
28 lines (23 loc) · 823 Bytes
/
use-interval.js
File metadata and controls
28 lines (23 loc) · 823 Bytes
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
import {useEffect, useRef, useState} from 'react'
function useInterval(callback, delay, limit) {
const [count, setCount] = useState(1)
const intervalRef = useRef()
const callbackRef = useRef(callback)
useEffect(() => {
callbackRef.current = callback
}, [callback]);
useEffect(() => {
console.log(delay, count, limit)
if ((typeof delay === 'number' && count <= limit) || (typeof delay === 'number' && !limit)) {
intervalRef.current = window.setInterval(() => {
setCount(c => c + 1)
callbackRef.current(count, setCount)
}, delay)
return () => {
window.clearInterval(intervalRef.current)
}
}
}, [delay, count]);
return intervalRef;
}
export default useInterval