Idrizi.A
Idrizi.A

Reputation: 12080

Error while using clearInterval()

I use the following code to hide and show a div every 1 sec

$(document).ready(function(e) {
    var acc = setInterval(function(){
        $("#element").fadeOut(function(){
            setTimeout(function(){
                $("#element").fadeIn()  
            }, 1000)    
        })
    }, 200)
})

$(window).load(function(){
    setTimeout(function(){
        clearInterval(acc);
    }, 10000)
})

The clearInterval() is not working as it should and I get the following error on Google Chrome:

Uncaught ReferenceError: acc is not defined

DEMO: http://jsfiddle.net/enve/4GWvM/

Upvotes: 1

Views: 592

Answers (2)

David G
David G

Reputation: 96855

Try redefining your acc variable outside the .ready callback.

var _acc = function(callback) {
    return setInterval(callback, 1000);
};

var acc = null;

$(document).ready(function() {
    acc = _acc(function() {
        $("#element").fadeOut(function(){
            setTimeout(function(){
                $("#element").fadeIn()  
            }, 1000)    
        })
    });
});

...

Upvotes: 2

Ram
Ram

Reputation: 144739

There is a scope issue in your code, you have defined the acc variable locally in the context of the document ready handler and it's not defined in the context of load handler.

Upvotes: 6

Related Questions