Verify whether the element retains the mouseenter event after a specified delay

I recently implemented some blocks with a mouseenter and mouseleave event.

<button onMouseEnter={this.MouseEnter}>hover</button>

MouseEnter(e) {
    setTimeout(() => {
        // Checking if the mouse is still on this element
        // Perform action
    }, 600);
}

However, I encountered an issue where moving the blocks quickly causes the last block to detect the mouseenter before the timeout, triggering the action even when not hovering over the block. This is a bug that I need to address so that the action only runs after 500ms of hovering over the block.

p.s: I am using react.js for this project

Answer №1

One crucial aspect to consider is the invalidation of the timeout callback when triggered by the mouseLeave event. It's essential to keep track of the returned value from setTimeout so that you can use clearTimeout before the timer runs out (or if the component unmounts!)

Below is the basic setup in a class-based component:

state = {
  hovered: false
};
timer;

mouseEnterHandler = () => this.setState({ hovered: true });
mouseLeaveHandler = () => this.setState({ hovered: false });

onTimeout = () => {
  // Perform action
};

clearTimer = () => {
  clearTimeout(this.timer);
};

componentDidUpdate() {
  const { hovered } = this.state;

  if (hovered) {
    this.timer = setTimeout(this.onTimeout, 500);
  } else {
    this.clearTimer();
  }
}

componentWillUnmount() {
  this.clearTimer();
}

Here is the equivalent logic for a functional component:

const [hovered, setHovered] = useState(false);

const mouseEnterHandler = () => sethovered(true);
const mouseLeaveHandler = () => sethovered(false);

const onTimeout = () => {
  // Perform action
};

useEffect(() => {
  const timer = hovered && setTimeout(onTimeout, 500);
  return () => {
    clearTimeout(timer);
  };
}, [hovered]);

https://codesandbox.io/s/pedantic-flower-wsp3z?expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...

The animation feature on the slideshow is dysfunctional

For this Vue component, I attempted to create a slideshow. The process is as follows: 1) Creating an array of all image sources to be included (array: pictures) 2) Initializing a variable(Count) to 0, starting from the beginning. 3) Adding v-bind:src=" ...

Create a link for editing in a data table that can filter based on multiple column values and also enable global search on specific custom

How can I generate an edit link with a function that requires multiple parameters extracted from different data columns received via ajax? I have come across the render callback, but it seems to only return one column value at a time and my requirement is ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

retrieve the source code from all .js links found within the document

There is a file labeled urls.txt. https://website.tld/static/main_01.js https://website.tld/static/main_02.js https://website.tld/static/main_03.js .... All the source code from every .js file in allsource.txt needs to be extracted. Instructions: To ge ...

Encountering a roadblock while trying to work with AngularJS Material radio buttons

In one of my projects, I have implemented a polling system where users can choose a question from a list and then proceed to the options page. On the options page, users can select their answer choices and submit their responses. The results are then displ ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Production pages encounter 'get' error when refreshed due to routing issues - Node.js, Express API with webpack and ReactJS frontend

I have set up my webpack configuration to compile my react app, and I am using Node.js as the server with Express middleware. Whenever I try to refresh a route on the production environment, for example /chefs, I receive an error. Below is my server.js s ...

Utilizing JSON Data for Dynamically Displaying Database Objects on a Google Map

After carefully reviewing the information provided in the initial responses and working on implementation, I am updating this question. I am currently utilizing the Google Maps API to incorporate a map into my Ruby on Rails website. Within my markets mode ...

Developing a innovative and interactive nested slider using Jssor technology

Trying to implement a dynamic jssor nested slider to showcase albums and images from a mySQL database. Everything works fine with a single album, but when there are two or more albums, the display gets messed up. I'm still learning JavaScript and JQue ...

Node.js process.exec() function allows you to asynchronously spawn a subprocess

After writing the code, I ran it and found that the terminal was unresponsive with no output, causing the program to be stuck. var util=require('util') var exec=require('child_process').exec; exec('iostat 5',function(err,stdo ...

Having Trouble Loading PHP File with Jquery

I've been struggling with using JQuery/Ajax to load the content of my PHP file into a div tag. Below is the code snippet from my page that attempts to load the file: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/ ...

Error: Comparison of two objects cannot be performed in Node.js due to AssertionError

Utilizing the functions below to retrieve a value from the application and compare it with the expected value. However, encountering issues with the output displayed. Seeking assistance in resolving this matter. getEleAttribute = async function(ele, attr) ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

Reacting to the state of a child component from the parent component

Apologies for coming back with another question so soon, but I'm struggling here! I spent hours yesterday trying to figure out how to pass data from a child component to its parent using React hooks, but my brain just won't cooperate. What I&ap ...

Utilize Laravel to trigger a route action based on a dropdown selection change, generating a unique URL

In my code, I have a dropdown select containing the list of the next 12 months: <select name="month" id="specificMonth"> @foreach(Carbon\CarbonPeriod::create(now()->startOfMonth(), '1 month', now()->addMon ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

Encountered an issue during the creation of a React app using create-react-app

Sorry! It seems like there was an error with the npm installation process. The system returned a code EPERM, which stands for permission error. This could be due to the system not allowing the creation of a directory at the specified path here. The operati ...

Issue with Bootstrap-vue pagination navigation not functioning correctly (unexpectedly refreshes upon clicking a page)

I recently updated my website's gallery pagination by following a helpful guide. However, I encountered a problem where clicking on a new page number refreshes the entire webpage, unlike the smooth transition shown in the tutorial. This is not the beh ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...