Alex
Alex

Reputation: 117

How to stop javascript/jquery from executing when another function call is made

My understanding of JavaScript is not super great, but I've been trying to use it to make some interactive features on my kids' website, experimonkey.com. One of my latest ideas was to have menu items on the homepage popup with additional information using JQuery's toggle() function when the user hovers over the corresponding menu item. This almost accomplishes what I want to do, except if you start hovering over the links too quickly, things get weird really fast... every single function call gets executed to completion and the browser starts to lag.

Is there a way to fix this so that only one element is in the queue at a time? Am I going about this totally wrong to begin with? Below is a sample of the code I'm using.

function show(id) {
  $(document).ready(function() {
    $("#" + id).slideToggle();
  });
}
.hidden {
  display: none;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<div class="col-6  col-sm-4 col-lg-2 tile p-1">
  <a href="/edu-center" onmouseenter="show('edu-center')" onmouseout="show('edu-center')">
    <div class="card">
      <div class="card-header" id="tile-edu-center"></div>
      <div class="card-body text-center">
        <h5>Edu-center</h5>
        <small id="edu-center" class="hidden">Science research and information for kids</small>
      </div>
    </div>
  </a>
</div>

Upvotes: 2

Views: 121

Answers (2)

Long Tran thanh
Long Tran thanh

Reputation: 86

You can use debounce to accomplish this. Basically, the debounce function delays the processing of event until the user has stopped for a predetermined amount of time. For example, use debounce(onClick, 3000) will only trigger onClick 2-times if two click actions is at least 3 seconds in between

Upvotes: 0

Nidhin Joseph
Nidhin Joseph

Reputation: 10237

An alternative is to make use of the :hover pseudo-class. Now, for the animation, you can use the max-height.

.hidden {
  display: inline-block;
  max-height: 0px;
  overflow: hidden;
}

small {
  transition: all 0.5s ease-in-out;
}

a:hover small {
  max-height: 1000px;
  height: auto;
  transition: all 1s ease-in-out;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<div class="col-6  col-sm-4 col-lg-2 tile p-1">
  <a href="/edu-center">
    <div class="card">
      <div class="card-header" id="tile-edu-center"></div>
      <div class="card-body text-center">
        <h5>Edu-center</h5>
        <small id="edu-center" class="hidden">Science research and information for kids</small>
      </div>
    </div>
  </a>
</div>

Upvotes: 1

Related Questions