javascriptmouseeventsettimeoutmouseovermouseout

Unable to work out the "setTimeout" function accordingly in JavaScript


Code :

function mouseSlideIn() {
  document.getElementById("box").style =
    "background: blue; height: 50px; width: 50px;";
}

function mouseSlideOut() {
  setTimeout(function() {
    document.getElementById("box").style = "";
    document.getElementById("eventDiv").style = "";
  }, 2000);
}
body {
  background: grey;
  margin: 0;
}

#eventDiv {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 90vh;
  background: powderblue;
  border-radius: 20px;
  transition: 0.8s;
  transition-timing-function: ease;
}

#box {
  position: relative;
  background: red;
  height: 150px;
  width: 150px;
  transition: 0.5s;
  transition-timing-function: ease;
}
<br>
<center>
  <div id="eventDiv" onmouseover="mouseSlideIn()" onmouseout="mouseSlideOut()">
    <div id="box"></div>
    <!--Above is the red box i.e. inside the main DIV-->
  </div>
</center>

Goal :

  1. When I hover over the id="eventDIV" (outer most div), the id="box" must shrink and change color.
  2. When I hover out of the id="eventDIV" , the id="box" must return to its original size & color.
  3. But, before the box returns to its original state, I want a delay of (let's say 2000ms ).
  4. This is achievable with the help of setTimeout function.

Problems :

  1. When I hover out of the id="eventDIV" before the setTimeout runs out which is 2000ms , it breaks the code.
  2. It doesn't run appropriately when I hover over again (i.e.): Even when the cursor is inside the id="eventDIV" , the mouseSlideOut() function gets executed, which was supposed to be called on onmouseout event; that is when I hover out.
  3. It keeps repeating the same mistake until I refresh the code.

What have I tried :

  1. I have tried using clearTimeout function, but its doesn't seems to help.
  2. Some other methods that didn't work.

Note:


Solution

  • You can achieve this with the clearTimeout-function. As you can also see in the docs, you need to set an ID for your timeout to be able to clear it.

    This should do the trick:

    let timeoutId;
    
    function mouseSlideIn() {
      document.getElementById("box").style =
        "background: blue; height: 50px; width: 50px;";
      clearTimeout(timeoutId);
    }
    
    function mouseSlideOut() {
      timeoutId = setTimeout(function () {
        document.getElementById("box").style = "";
        document.getElementById("eventDiv").style = "";
      }, 2000);
    }