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
// React hook for creating a typewriter effect
/** @jsxImportSource https://esm.sh/react */
import { useEffect, useRef, useState } from "https://esm.sh/react";
const rand = (min, max) => Math.floor(Math.random() * (max - min) + min);
export const useTypewriter = (text: string, speed: number = 16, off: number = 12) => {
const [i, setI] = useState<number>(1);
useEffect(() => {
if (i > text.length) return;
let delay = rand(speed, speed + off);
const id = setTimeout(() => {
setI(i => i + 1);
}, delay);
return () => {
clearTimeout(id);
};
}, [text, i]);
// console.log(i, text.length);
return text.slice(0, i);
};
export function Typewriter({ text }) {
const res = useTypewriter(text);
return <>{res}</>;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 28, 2024