-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseTypingEffect.ts
More file actions
41 lines (31 loc) · 1.11 KB
/
useTypingEffect.ts
File metadata and controls
41 lines (31 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { useEffect, useRef, useState } from 'react';
const useTypingEffect = (fullText: string, duration: number) => {
const [displayedText, setDisplayedText] = useState('');
const rafIdRef = useRef<number | null>(null);
useEffect(() => {
let startTime: number | null = null;
const charArray = Array.from(fullText);
const totalChars = charArray.length;
const step = (timestamp: number) => {
if (startTime === null) {
startTime = timestamp;
}
const elapsed = timestamp - startTime;
const progress = duration <= 0 ? 1 : Math.min(elapsed / duration, 1);
const charsToShow = Math.round(progress * totalChars);
setDisplayedText(charArray.slice(0, charsToShow).join(''));
if (progress < 1) {
rafIdRef.current = requestAnimationFrame(step);
}
};
rafIdRef.current = requestAnimationFrame(step);
return () => {
if (rafIdRef.current !== null) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
};
}, [fullText, duration]);
return displayedText;
};
export default useTypingEffect;