I have functional component in reactjs, and I am trying to do timeout on mouse hover over menu, which is fine and work well, but I dont know how to clear this timeout in other function in this same functional component, is there some solution for this? I primary use hooks. I found some hooks timeout, but not work well. Thanks very much
Clearing setTimeout A setTimeout timer must be cleared and handle properly, otherwise, you may experience adverse side effects in your code. To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout().
No, setTimeout stops running after 1 call. In order to stop setInterval however, you must use clearInterval . If you create an endless loop of setTimeout then clearTimeout could be used.
To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.
How to use setTimeout in React. The setTimeout function accepts two arguments: the first is the callback function that we want to execute, and the second specifies the timeout in milliseconds before the function will be called. setTimeout(() => console. log('Initial timeout!'
You can use something like this.
import React, { useRef } from 'react';
const Menu = () => {
const timerRef = useRef(null);
const onMouseEnter = () => {
timerRef.current = setTimeout(() => {}, 1000);
}
const onMouseLeave = () => {
if(timerRef.current) {
clearTimeout(timerRef.current);
}
}
return <div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />
}
What's happening here is that, we are saving the timer's reference in a react ref. This can then be used to check and clear the timer in another function.
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