react-simple-typewriter
react-simple-typewriter copied to clipboard
Pause / Resume?
I need the effect to pause once the document.hidden = true
and resume once document.hidden = false
. I can't seem to get a handle on this as it runs while the document isn't being viewed and slowing down the browser especially if typewriting for a long time. I tried using document.addEventListener("visibilitychange")
and had no luck. Thanks!
Now that I thought about it, the only way to pause/resume is to pause/resume the entire useTypewriter hook... In order to do so, I created two Components and it's working perfectly. Sharing it below in case you want to add document.hidden document.blur and document.focused pausing/resuming into your hook and/or component.
const TypingEffect = ({words, loop, delaySpeed, onType, cursorColor}) => {
const [text] = useTypewriter({
words,
loop: typeof loop === 'boolean' ? loop : true,
delaySpeed: delaySpeed || 900,
onType: onType || null
});
return (
<>
<span className="mx-auto">{text}</span>
<Cursor cursorColor={(cursorColor || 'black')} />
</>
);
};
const TypingEffectController = ({words, loop, delaySpeed, onType, cursorColor}) => {
const [showTyping, setShowTyping] = useState(document.hasFocus());
const [currentWord, setCurrentWord] = useState(words[0]);
const onVisibilityChange = e => {
setShowTyping(document.hasFocus());
}
const onTyped = (wordIndex) => {
setCurrentWord(words[wordIndex]);
if ( typeof onType === 'function' ) onType(wordIndex);
}
useEffect(()=>{
document.onvisibilitychange = onVisibilityChange;
document.onblur = onVisibilityChange;
document.onfocus = onVisibilityChange;
}, []);
return (
<>
{showTyping && <TypingEffect
words={words} onType={onTyped} loop={loop}
delaySpeed={delaySpeed} cursorColor={cursorColor}
/>}
{!showTyping && <span>{currentWord}</span>}
</>
);
};
Currently when you blur document focus or it's document.hidden, the typewriter is replaced with the last word and stops rendering. Once you focus or become not hidden, it starts from the beginning. It would be nice to have it resume to the word index where it left off, but I'll have to save that for another day.