Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do timeout and then clear timeout in react functional component?

Hi,

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

like image 562
LiH Avatar asked Jun 14 '19 12:06

LiH


People also ask

How do you clear setTimeout in React functional component?

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().

Does setTimeout need to be cleared?

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.

How do I clear set timeout?

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 do you create a timeout in React?

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!'


1 Answers

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.

like image 194
johnny peter Avatar answered Oct 21 '22 05:10

johnny peter