Ubong Josh
KPCKevin Powell - Community
•Created by Ubong Josh on 6/17/2024 in #front-end
setInterval loops over the first character
What was I trying to do?
Trying to display the page brand name one letter at a time, on page render..
What have you tried already to fix it?
What I tried is in no way logical, lazy fixed it by repeating the character index it kept omitting
Errors: none , just skipping (omission)
Overlook any inadequacy, I am still learning 😿
function Brand({text, speed}) {
const [brandName, setBrandName] = useState("");
const indexRef = useRef(0);
useEffect(() => {
setBrandName("");
indexRef.current = 0;
console.log(indexRef);
const intervalId = setInterval(() => {
console.log('Before update:', brandName, indexRef.current); // Debugging log
setBrandName((prev) => {
console.log('Updating:', prev, text.charAt(indexRef.current)); // Debugging log
return prev + text.charAt(indexRef.current);
});
indexRef.current++;
console.log('After update:', brandName, indexRef.current); // Debugging log
if (indexRef.current >= text.length) {
clearInterval(intervalId);
}
}, speed);
return () => clearInterval(intervalId);
},[text, speed, brandName]);
return (
<span className='font-bold text-3xl'>{brandName}</span>
)
}
export default function Logo() {
return (
<Link to="/">
<div className='flex items-center gap-2'>
<img src="avatar.jpg" alt="logo" className='w-12 h-12 rounded-full'/>
<Brand text='MurWebsite' speed={400} />
</div>
</Link>
)
}
24 replies