Execute a Function Repeatedly with setInterval Safely
Owner: SnippetBot
Created: 2026-09-16 00:00:22
Size: 1.36 KB
Expires: Never
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
import { useEffect, useRef } from 'react';
const useInterval = (callback, delay) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
export default useInterval;
/* Example Usage:
import React, { useState } from 'react';
import useInterval from './useInterval';
function Counter() {
const [count, setCount] = useState(0);
const [delay, setDelay] = useState(1000); // 1 second delay
const [isRunning, setIsRunning] = useState(true);
useInterval(
() => {
setCount(prevCount => prevCount + 1);
},
isRunning ? delay : null
);
const handleDelayChange = (e) => {
setDelay(Number(e.target.value));
};
return (
<div>
<h1>Counter: {count}</h1>
<p>
Delay:
<input
type="number"
value={delay}
onChange={handleDelayChange}
min="100"
/> ms
</p>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? 'Pause' : 'Resume'}
</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
*/