Vasile Labici
Vasile Labici

Reputation: 13

Stop function on mouseleave

I am having issues with a function that is trigger on mouseenter and it loops. The problem is that I want to function to stop on mouseleave.

Tried a few things but nothing seemed to work as expected.

HTML

<div class="trigger">Hover me to trigger animation</div>

<div class="logo-tagline">
  <span>Simple.</span>
  <span>Fast.</span>
  <span>Around you.</span>
</div>

JQuery

$( ".trigger" ).mouseenter(function() {
  function highlight(items, index) {
    index = index % items.length;
    items.removeClass("-visible");
    items.eq(index).addClass('-visible');   
    setTimeout(function() {
      highlight(items, index + 1)
    }, 1000);
  }
  
  highlight($('.logo-tagline span'), 0);
});


Link to my pen: https://codepen.io/Vlasin/pen/YzZxqNp?editors=1010

Upvotes: 1

Views: 287

Answers (2)

Harsh Gundecha
Harsh Gundecha

Reputation: 1197

  • you just need to clear the setTimeout, something as following

  • Note though that depending upon whether or not you want to hide the text again is up to you so handle that accordingly.

      let timeoutFunc;
      function highlight(items, index) {
          index = index % items.length;
          items.removeClass("-visible");
          items.eq(index).addClass('-visible');   
          timeoutFunc = setTimeout(function() {
              highlight(items, index + 1)
          }, 1000);
      }
    
      $( ".trigger" ).mouseenter(function() {
          highlight($('.logo-tagline span'), 0);
      });
    
      $( ".trigger" ).mouseleave(function() {
          $('.-visible').removeClass("-visible");
          clearTimeout(timeoutFunc);
      });
    

Upvotes: 1

Dibash Sapkota
Dibash Sapkota

Reputation: 665

check this working example: https://codepen.io/DibashSapkota/pen/YzZxrXw?editors=0010

$( ".trigger" ).mouseenter(startInterval);
$( ".trigger" ).mouseleave(stopInterval);

// You'll need a variable to store a reference to the timer
var timer = null;

function startInterval() {

  /* Your Function Code HERE */

  // Then you initilize the variable
  timer = setInterval(function() {
    console.log("Foo Executed!");
  }, 1500);
}

function stopInterval() {
  // To cancel an interval, pass the timer to clearInterval()
  clearInterval(timer);
}

Upvotes: 0

Related Questions