0

I'm trying to make image rotator with Jquery, but my rotator won't stop when I put the mouse over the images, so I'm guessing that something's wrong with clearTimeout.
Here's my code:

$(document).ready(function () {
    var o = 0
    var t = null;
    stop = false;
    $("img:gt(0)").hide();
    broj = ($("img").size());

    function promena() {
        o++;
        if (o == broj) {
            o = 0;
            $("img:lt(3)").hide(function () {
                $("img").eq(3).delay(1000).fadeOut(1000);
            });
        }
        $("img").eq(o).delay(1000).fadeIn(1000, function () {
            t = setTimeout(promena, 1000);
        });
    };

    t = setTimeout(promena, 1000);
    $("div img").mouseover(function () {
        clearTimeout(t);
    });
});

And here's HTML:

<html>
<head>
<title>M</title>
</head>
<body>
 <div>
 <img src="images/1.jpg"    />
 <img src="images/2.jpg"    />
 <img src="images/3.jpg"    />
 <img src="images/4.jpg"    />
 </div>
</body>
</html>

If it means anything, all of my images are positioned absolutely with img{position:absolute}

mVChr
  • 49,587
  • 11
  • 107
  • 104
Mentalhead
  • 1,501
  • 5
  • 20
  • 28
  • 2
    Hmm Im not sure it works fine for me http://jsfiddle.net/loktar/qNv3u/1/ – Loktar Mar 28 '11 at 17:57
  • It doesn't work always, in fact it only works if you put a mouse over in first few seconds after the clearTimeout starts, and I want to be able to stop the fadeOut at any time with the mouseover and continue with the animations on mouseout. – Mentalhead Mar 29 '11 at 05:20

1 Answers1

1

Your code is essentially doing this:

  1. timeout timer running for one second
  2. delay running for one second
  3. fade running for one second
  4. repeat

--> if you trigger the mouseover event, and hence call clearTimeout at any point other than (1), you aren't clearing any running timer.

In other words, if you do this after, lets say 1.5 seconds, the delay is still running, then the fade, and then you call setTimeout again - so you are attempting to clearTimeout before calling setTimeout.

You should probably call .stop() to stop the delay and fade queue, and prevent setTimeout running when they are complete.

Graza
  • 5,010
  • 6
  • 32
  • 37
  • Thanks for detailed explanation, after adding .stop(true,true) to mouseover, and changing a code a bit, everything works great. Thanks a lot. – Mentalhead Mar 29 '11 at 16:08