July
July

Reputation: 566

JQuery setInterval is not working after multiple hover sequence

I'm trying to emulate the footer of a powerpoint presentation. So this is the code

$(function() {
        $('.presentation').on({
          mouseleave: function() {	     
			setInterval(function () {
			if(!$("input").is(":focus") && !$(".presentation:hover").length > 0 && !$('.bp-controls').hasClass('show')){		  
		       $('.bp-controls').fadeOut();	
               $('.bp-controls').removeClass('show');				   
		         }
		     }, 4000);
          },
          mouseenter: function() {
		 $('.bp-controls').fadeTo(500, 1, function() {
           // Animation complete.
		      $('.bp-controls').addClass('show');
             });	            
           }
        });
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="presentation">
         <img src="Main.png" width="50%">
         <div class="bp-controls"><input type="number" pattern="[0-9]*"></div>
        </div>

I don't understand why setInterval works the first and maybe the second time when the document is ready but then it doesn't work anymore.

Upvotes: 0

Views: 60

Answers (1)

epascarello
epascarello

Reputation: 207527

You are adding multiple intervals. You need to clear then when you leave. Should be a timeout also, I doubt you want to keep firing it.

$('.presentation').on({
  mouseleave: function() {       
    this.timer = setTimeout(function () {}, 4000);
  },
  mouseenter: function() {
    if (this.timer) window.clearTimeout(this.timer)
  }
});

Upvotes: 1

Related Questions