简体   繁体   中英

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 .

You just have to create a global timer variable that will store setInterval() value, so that you can use it to stop setInterval running.

    var timer = undefined;

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

    function kill() {
        timer && clearInterval(timer)
    }

--------- this is html code

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

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> 

You need to declare timer variable outside function to be used by another function Replace your JS with :

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

function kill() {
    clearInterval(timer)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM