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...

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • 1
    And what is it supposed to do? What do you mean by not working? – Jakub Hampl Apr 01 '11 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. –  Apr 01 '11 at 18:47
  • And are you sure the problem isn't somewhere else? Is `stopTimer` even being called? – Jakub Hampl Apr 01 '11 at 18:52

1 Answers1

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(); });
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
  • 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. –  Apr 01 '11 at 19:17
  • Update the question with the full source - it's hard to specluate about code you don't see. – Jakub Hampl Apr 01 '11 at 19:34