2020-06-29 10:35:14 +00:00
|
|
|
/*
|
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2021-06-29 12:11:58 +00:00
|
|
|
import { useEffect, useRef, useState } from "react";
|
2020-06-29 10:35:14 +00:00
|
|
|
|
|
|
|
type Handler = () => void;
|
|
|
|
|
|
|
|
// Hook to simplify timeouts in functional components
|
2023-01-12 13:25:14 +00:00
|
|
|
export const useTimeout = (handler: Handler, timeoutMs: number): void => {
|
2020-06-29 10:35:14 +00:00
|
|
|
// Create a ref that stores handler
|
|
|
|
const savedHandler = useRef<Handler>();
|
|
|
|
|
|
|
|
// Update ref.current value if handler changes.
|
|
|
|
useEffect(() => {
|
|
|
|
savedHandler.current = handler;
|
|
|
|
}, [handler]);
|
|
|
|
|
|
|
|
// Set up timer
|
|
|
|
useEffect(() => {
|
2022-11-30 11:32:56 +00:00
|
|
|
const timeoutID = window.setTimeout(() => {
|
2023-02-16 17:21:44 +00:00
|
|
|
savedHandler.current?.();
|
2020-06-29 10:35:14 +00:00
|
|
|
}, timeoutMs);
|
|
|
|
return () => clearTimeout(timeoutID);
|
|
|
|
}, [timeoutMs]);
|
|
|
|
};
|
|
|
|
|
|
|
|
// Hook to simplify intervals in functional components
|
2023-01-12 13:25:14 +00:00
|
|
|
export const useInterval = (handler: Handler, intervalMs: number): void => {
|
2020-06-29 10:35:14 +00:00
|
|
|
// Create a ref that stores handler
|
|
|
|
const savedHandler = useRef<Handler>();
|
|
|
|
|
|
|
|
// Update ref.current value if handler changes.
|
|
|
|
useEffect(() => {
|
|
|
|
savedHandler.current = handler;
|
|
|
|
}, [handler]);
|
|
|
|
|
|
|
|
// Set up timer
|
|
|
|
useEffect(() => {
|
2022-11-30 11:32:56 +00:00
|
|
|
const intervalID = window.setInterval(() => {
|
2023-02-16 17:21:44 +00:00
|
|
|
savedHandler.current?.();
|
2020-06-29 10:35:14 +00:00
|
|
|
}, intervalMs);
|
|
|
|
return () => clearInterval(intervalID);
|
|
|
|
}, [intervalMs]);
|
|
|
|
};
|
|
|
|
|
|
|
|
// Hook to simplify a variable counting down to 0, handler called when it reached 0
|
2023-01-12 13:25:14 +00:00
|
|
|
export const useExpiringCounter = (handler: Handler, intervalMs: number, initialCount: number): number => {
|
2020-06-29 10:35:14 +00:00
|
|
|
const [count, setCount] = useState(initialCount);
|
|
|
|
useInterval(() => setCount((c) => c - 1), intervalMs);
|
|
|
|
if (count === 0) {
|
|
|
|
handler();
|
|
|
|
}
|
|
|
|
return count;
|
|
|
|
};
|