I am doing a simple animation in a next.js app.
let flipInterval = useRef();
const startAnimation = () => {
flipInterval.current = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping);
}, 10000);
};
for flipInterval.current
I am getting "Type 'Timeout' is not assignable to type 'undefined'". So i checked how to use Timeout type, I see that people are using but thats not working.
let flipInterval = useRef<typeof window.settimeout>();
I also passed number useRef<number>()
this time I am getting "Type 'Timeout' is not assignable to type 'number'"
this did not work neither
let flipInterval = useRef<typeof window.setInterval>();
const intervalRef: { current: NodeJS.Timeout | null } = useRef(null);
const startAnimation = () => {
const id = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping);
}, 10000);
intervalRef.current = id;
};
const clear = () => {
clearInterval(intervalRef.current as NodeJS.Timeout);
};
you need to pass the proper return value type of setInterval
. for this use ReturnType
:
const flipInterval = useRef<ReturnType<typeof setInterval>>(null)
How i'm using
*It is preferable to set initialValue of useRef. Thats why null.
const timeout = useRef<NodeJS.Timeout | null>(null);
timeout.current = setTimeout(() => someAction()), 500);
useEffect(() => {
return () => clearTimeout(timeout.current as NodeJS.Timeout);
}, []);
If you are debouncing and need to clear a timeout null
needs to be handled
Posting as this might help others due to the title of the question.
const flipInterval:{current: NodeJS.Timeout | null} = useRef(null)
const startAnimation = () => {
flipInterval.current && clearTimeout(scrollTimeout.current);
flipInterval.current = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping)
}, 10000)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With