Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Last active December 19, 2024 20:11
Show Gist options
  • Save alexanderson1993/e47194655ef33951b4c3b00c3bcc704d to your computer and use it in GitHub Desktop.
Save alexanderson1993/e47194655ef33951b4c3b00c3bcc704d to your computer and use it in GitHub Desktop.
import { ButtonHTMLAttributes, useRef, useEffect } from "react";
export function ClickAndHoldButton({
action,
delay = 500,
loopDuration = 100,
...rest
}: {
action: () => void;
delay?: number;
loopDuration?: number;
} & ButtonHTMLAttributes<HTMLButtonElement>) {
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
const actionRef = useRef(action);
useEffect(() => {
actionRef.current = action;
}, [action]);
const performAction = () => {
actionRef.current();
timeoutRef.current = setTimeout(performAction, loopDuration);
};
return (
<button
{...rest}
onPointerDown={() => {
action();
timeoutRef.current = setTimeout(performAction, delay);
}}
onPointerUp={() => {
clearTimeout(timeoutRef.current);
}}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment