Created
August 21, 2023 10:49
-
-
Save guillermodlpa/62cf969987ae5bcbc6eebdaf9ef30cd0 to your computer and use it in GitHub Desktop.
hook to autoplay a video
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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