Search code examples
javascriptscrollsetintervalmouseovermouseenter

How to stop a setInterval fired by mouseenter, upon mouseleave?


I've managed to get arrows which scroll the overflow of a div on mouseenter to work. The problem is that the script not only doesn't stop on mouseleave, but prevents to scroll the div opposite side manually.

JS

function scroll_right() {
        var elmnt = document.getElementsByClassName("thumbnails")[0];
            elmnt.scrollLeft += 50;
        var timer = setInterval(scroll_right, 300); 
}

function kill() {
        clearInterval(timer)
}

And the arrow

<img class="arrow" 
 onmouseenter="scroll_right()"
 onmouseleave="kill()" 
 src="https://image.flaticon.com/icons/svg/126/126490.svg">

My idea was that scroll_right function gets fired on mouseenter, and the timer inside of it, gets deactivated on mouseleave.


Solution

  • The timer is set every time the scroll_right function runs. There will be infinitely many timer running at the some time after a while. You can try using setTimeout function instead of the below one. Also, the scope of timer is limited to the function in your code.

    var timer = undefined;
    
    function scroll_right() {
      var elmnt = document.getElementsByClassName("thumbnails")[0];
      elmnt.scrollLeft += 50;
      if (!timer) {
        timer = setInterval(scroll_right, 300);
      }
    }
    
    function kill() {
      if (timer) {
        clearInterval(timer);
        timer = undefined;
      }
    }
    <div class="thumbnails" onmouseenter="scroll_right()" onmouseleave="kill()" style="width:150px;overflow:auto">
      <img class="arrow" src="https://image.flaticon.com/icons/svg/126/126490.svg" width="500px">
    </div>