5

I have gone through most of the code here and tried several ways to get clearInterval to work and for some reason it is just not working, although it is a basic and simple problem.

Here is the code and I want to know WHY it isn't working, not just get the code done for me.

var myTimer;

function startTimer() {
    myTimer = window.setInterval( function() {
        $('#randomImage').fadeTo('slow',0.0).addClass("changeBg_" + current);
        var current = Math.round(Math.random() * 4) + 1;
        $('#randomImage').fadeTo('slow',1.0).addClass("changeBg_" + current);
    }, 5000);
};

function stopTimer(){
    window.clearInterval(myTimer);
    $('#randomImage').fadeTo('slow',0.0);

}

Thanks In Advance from a Newbie...

3
  • 1
    And what is it supposed to do? What do you mean by not working? Commented Apr 1, 2011 at 18:41
  • starTimer() rotates css classes randomly every 5 seconds and stopTimer() should clear the setInterval put in startTimer() but it does not stop the setInterval. Commented Apr 1, 2011 at 18:47
  • And are you sure the problem isn't somewhere else? Is stopTimer even being called? Commented Apr 1, 2011 at 18:52

1 Answer 1

6

Your code is fine, it works perfectly. It must be a problem with the code calling it. Check out this fiddle.

var myTimer;

function startTimer() {
    myTimer = window.setInterval( function() {
        $('#randomImage').fadeTo('slow',0.0).addClass("changeBg_" + current);
        var current = Math.round(Math.random() * 4) + 1;
        $('#randomImage').fadeTo('slow',1.0).addClass("changeBg_" + current);
    }, 5000);
};

function stopTimer(){
    window.clearInterval(myTimer);
    $('#randomImage').fadeTo('slow',0.0);

}

startTimer();
$('#randomImage').click(function() { stopTimer(); });
Sign up to request clarification or add additional context in comments.

2 Comments

Your right Jakub...I added $('#randomImage').click(function() { stopTimer(); }); as a call instead of the Div onclick="stopTimer()" and it worked... can you explain why please.
Update the question with the full source - it's hard to specluate about code you don't see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.