I am building a link component using react js and gsap for animation, what I want to do is when I hover I want the animation to start, and while hovering it should keep repeating but after I the mouse leave I want it to resume the animation first and then kill it so it shouldn't kill animation immediately.
const Link = forwardRef<HTMLAnchorElement, LinkProps>(
({ children, variant, ...props }, ref) => {
const textRef = useRef<HTMLAnchorElement>(null);
const tl = useRef<GSAPTimeline>();
useEffect(() => {
if (textRef.current) {
const ourText = new SplitType(textRef.current, {
tagName: "span",
types: "words, chars",
wordClass: "",
charClass: "",
});
const chars = ourText.chars;
tl.current = gsap.timeline({
paused: true,
});
tl.current
.to(chars, {
opacity: 0.2,
ease: "power2.inOut",
stagger: {
amount: 0.4,
ease: "none",
},
})
.to(
chars,
{
opacity: 1,
ease: "power2.inOut",
stagger: {
amount: 0.4,
ease: "none",
},
},
"<+=0.3"
);
}
}, []);
const handleMouseEnter = () => {
tl.current?.restart().repeat(-1);
};
const handleMouseLeave = () => {
if (tl.current) {
tl.current.resume().kill();
}
};
return (
<a
ref={textRef}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
className={cn(linkStyle({ variant }))}
{...props}
>
{children}
</a>
);
}
);