How can I make my setTimeouts get stopped here?

The behavior I'm trying to achieve is this:

On hover/mouseenter, change the background image from the placeholder to a gif whose positions changes in order to achieve an animated effect, then go back to the placeholder when the mouse leaves.

My code is

    $('.filmstrip').mouseenter(function(){
        var $that = $(this),
               w = $that.width(),
              fr = $that.attr('data-framerate');
        $that.css('background-image','url('+$that.attr('data-gifurl')+')');
        for ( var i = 1, n = $that.attr('data-ticks'); i <= n; ++i )
        {
            (function(j){
               setTimeout(function(){
                  $that.css('background-position-x','-'+(w*j)+'px');
               }, j*fr);
            })(i);
        }
        $that.bind('mouseleave',function(){
            $that.css('background-image','url('+$that.attr('data-placeholder')+')').css('background-position-x','0');
        });
    }); 

and the bug I'm having is that if the gif hasn't finished animating, then the

.css('background-position-x','0')

part of

$that.css('background-image','url('+$that.attr('data-placeholder')+')').css('background-position-x','0');
            });

doesn't work because the background position is still being moved by the animation. So I need some way to first stop the setTimeout stuff if it isn't finished running. Any idea how I can do that?

Answers 1

  • U can use clearTimeout to stop setTimeOut.

    Working Demo-

    var myVar;
    
    function myFunction() {
        myVar = setTimeout(function(){ alert("Hello"); }, 3000);
    }
    
    function myStopFunction() {
        clearTimeout(myVar);
    }
    <p>Click the first button to alert "Hello" after waiting 3 seconds.</p>
    <p>Click the second button to prevent the first function to execute. (You must click it before the 3 seconds are up.)</p>
    
    <button onclick="myFunction()">Try it</button>
    <button onclick="myStopFunction()">Stop the alert</button>

    More-

    Mozilla Developer Network

    and

    W3School


Related Articles