Simple javascript or jQuery clearInterval issue

I did most of the code here and tried several ways to get clearInterval to work, and for some reason it just doesn't work, although this is a basic and simple problem.

Here is the code, and I want to know WHY it does not work, and not just make the code 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 advancement from the beginner ...

+5
source share
1 answer

Your code is fine, it works great. This should be a problem with the code calling it. Check out this script .

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(); });
+6
source

All Articles