Skip to content

Instantly share code, notes, and snippets.

@guillermodlpa
Created August 21, 2023 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillermodlpa/62cf969987ae5bcbc6eebdaf9ef30cd0 to your computer and use it in GitHub Desktop.
Save guillermodlpa/62cf969987ae5bcbc6eebdaf9ef30cd0 to your computer and use it in GitHub Desktop.
hook to autoplay a video
import { MutableRefObject, useEffect } from 'react';
const AUTO_PLAY_DELAY = 1500;
const PLAY_ERROR_NO_INTERACTION =
"play() failed because the user didn't interact with the document first";
export default function useAutoplay(
videoRef: MutableRefObject<HTMLVideoElement | HTMLAudioElement | undefined>,
isActive: boolean,
) {
useEffect(() => {
if (videoRef.current) {
if (isActive) {
const timeout = setTimeout(() => {
if (videoRef.current) {
videoRef.current.play().catch((error: Error) => {
const isAcceptableError =
typeof error.message === 'string' &&
error.message.includes(PLAY_ERROR_NO_INTERACTION);
if (!isAcceptableError) {
throw error;
}
});
}
}, AUTO_PLAY_DELAY);
return () => {
clearTimeout(timeout);
};
} else {
videoRef.current.pause();
}
}
}, [videoRef, isActive]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment