run an event if it passes x seconds running?

0

This is my code that makes a call Ajax:

    $(".card").hover(function (event) {
    console.log(event)
    if (Math.round(event.timeStamp) >= 4000) {
      let team_id = parseInt($(this).find("span:first-child").html());
      var carta = this;
      $.ajax({
        method: "POST",
        url: "/team/" + team_id,
        dataType: "JSON",
        timeout: 1000,
        error: function (error) {
          console.log(error);
        },
        success: function (res) {
          $(carta).append(plantilla_teams(res.id, res.plays_lose, res.plays_win))
        }

      })
    }


  }, function () {
    if ($(this).has("div.card-detalle")) {
      $(this).find("div.card-detalle").remove();
    }
  })
}

Once the event is activated, in this case it is "mouseEnter", if it passes X seconds in the element, just execute the instructions:

    
asked by 13.09.2017 в 17:27
source

1 answer

1

If I have not understood you correctly, you want to execute a code if the mouse passes more than X seconds on the element. For this you should use the setTimeout method to set the code to execute and the time and clearTimeout to cancel the execution in case the mouse leaves the element before the time elapsed:

$(function(){
  var hoverTimeout;
  function mouseIn(){
    hoverTimeout = setTimeout(function(){ console.log('Han pasado 4 segundos'); }, 4000);
  }
  function mouseOut(){
    clearTimeout(hoverTimeout);
  }
  
  $('#card').hover(mouseIn, mouseOut);
});
#card{
  width: 100px;
  height: 100px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="card"></div>
    
answered by 13.09.2017 / 17:39
source