Jquery - Timeout Function bugging script
<p>My problem: If you click on one link, then immediately on another the images start to stack up and the auto switching occurs every few seconds, not the defined times in the script leading me to think the problem is with <code>setInterval()</code> and <code>setTimeout()</code>. Also the script times out if left to it's own devices, after a few mins the image remains blank.</p>

<p>This script changes an image based on two factors:</p>

<ol>
<li>SetInterval() - Changes to the next image every 15 seconds</li>
<li>.click() - Changes to the next image if a user clicks on the link</li>
</ol>

<p><code>a</code> elements all have class (a1, a2, a3) and the active link has class 'a-active'</p>

<p>I'm sure the problem lies in this with the setTimout() but I'm not sure:</p>

<pre><code>var rotateTimer = setInterval(rotateImg,15000);

$('#feature-links a').click(function() {

    if (!$(this).hasClass('a-active')) {

        clearInterval(rotateTimer);
        switchToImg($(this).attr('class'));

        setTimeout(function() {
            rotateTimer = setInterval(rotateImg, 15000);
        }, 15000);

    }
});
</code></pre>

<p>The logical flow here is:</p>

<ol>
<li>call <code>rotateImg()</code> every 15 seconds</li>
<li>If the <code>a</code> element clicked on does not have class <code>a-active</code> :</li>
<li>clear the timer</li>
<li>switch the image to the one specified by the <code>a</code> element</li>
<li>set a timeout of 15 seconds, on callback restart the timer (Aggregate of 30 secs)</li>
<li>Resume normal rotate every 15 seconds.</li>
</ol>

<p>example: <a href="http://www.web-frame.co.uk/dev" rel="nofollow">http://www.web-frame.co.uk/dev</a>  </p>

<p>The switchToImg func is as follows:</p>

<pre><code>function switchToImg(image) {
    var $featureImage = $('#feature-image');        
    $featureImage.fadeOut(200, function() {
        $featureImage.css('background-image', 'url(images/main_' + image + '.jpg)').fadeIn(200);
        $('#feature-detail div').removeClass('d-active').filter('.d' + image).addClass('d-active');
    });
    $('#feature-links a').removeClass('a-active').filter('.' + image).addClass('a-active');
};
</code></pre>

<p>The rotateImg() func is as follows:</p>

<pre><code>function rotateImg() {
    var next = 'a' + (parseInt($('#feature-links a.a-active').attr('class').match(/[0-9]/),10)+1);

    if (!$('#feature-links a').hasClass(next))
        next = 'a1';
    switchToImg(next);
}
</code></pre>

<p>Thanks for any help given (again)! :)</p>
