|
| 1 | +/* |
| 2 | +Copyright 2020 The Matrix.org Foundation C.I.C. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import {useEffect, useRef, useState} from "react"; |
| 18 | + |
| 19 | +type Handler = () => void; |
| 20 | + |
| 21 | +// Hook to simplify timeouts in functional components |
| 22 | +export const useTimeout = (handler: Handler, timeoutMs: number) => { |
| 23 | + // Create a ref that stores handler |
| 24 | + const savedHandler = useRef<Handler>(); |
| 25 | + |
| 26 | + // Update ref.current value if handler changes. |
| 27 | + useEffect(() => { |
| 28 | + savedHandler.current = handler; |
| 29 | + }, [handler]); |
| 30 | + |
| 31 | + // Set up timer |
| 32 | + useEffect(() => { |
| 33 | + const timeoutID = setTimeout(() => { |
| 34 | + savedHandler.current(); |
| 35 | + }, timeoutMs); |
| 36 | + return () => clearTimeout(timeoutID); |
| 37 | + }, [timeoutMs]); |
| 38 | +}; |
| 39 | + |
| 40 | +// Hook to simplify intervals in functional components |
| 41 | +export const useInterval = (handler: Handler, intervalMs: number) => { |
| 42 | + // Create a ref that stores handler |
| 43 | + const savedHandler = useRef<Handler>(); |
| 44 | + |
| 45 | + // Update ref.current value if handler changes. |
| 46 | + useEffect(() => { |
| 47 | + savedHandler.current = handler; |
| 48 | + }, [handler]); |
| 49 | + |
| 50 | + // Set up timer |
| 51 | + useEffect(() => { |
| 52 | + const intervalID = setInterval(() => { |
| 53 | + savedHandler.current(); |
| 54 | + }, intervalMs); |
| 55 | + return () => clearInterval(intervalID); |
| 56 | + }, [intervalMs]); |
| 57 | +}; |
| 58 | + |
| 59 | +// Hook to simplify a variable counting down to 0, handler called when it reached 0 |
| 60 | +export const useExpiringCounter = (handler: Handler, intervalMs: number, initialCount: number) => { |
| 61 | + const [count, setCount] = useState(initialCount); |
| 62 | + useInterval(() => setCount(c => c - 1), intervalMs); |
| 63 | + if (count === 0) { |
| 64 | + handler(); |
| 65 | + } |
| 66 | + return count; |
| 67 | +}; |
0 commit comments