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

        var $that = $(this),
               w = $that.width(),
              fr = $that.attr('data-framerate');
        for ( var i = 1, n = $that.attr('data-ticks'); i <= n; ++i )
               }, j*fr);

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


part of


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() {
    <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>


    Mozilla Developer Network



Related Articles