anon
anon

Reputation: 1117

jQuery clearInterval not working

I have the following hover function

function tt_attachToBase(){
        jQuery.each(bases,
            function(index,base){

                jQuery(base).hover(function() {  
                         jQuery(base).showTipTimer = setInterval( function(){tt_locateBase(base);} , 3000 ); 
                             },  
                            function() {  
                                clearInterval(jQuery(base).showTipTimer);
                                tt_hideTip();
                                    }

                    }); 
            }

        );

inside tt_locateBase() I also clear interval like this

tt_locateBase(base){
clearInterval(jQuery(base).showTipTimer);
//code to sidplay tooltip
}

the tooltip does display after an interval, but the interval it seems is never cleared since the tooltip keep recurring over base. what am I doing wrong?

Upvotes: -1

Views: 1896

Answers (2)

Jon Gauthier
Jon Gauthier

Reputation: 25582

Setting a property to the return value of jQuery(base) will only affect that specific object. If you fetch jQuery(base) a second time it won't be carrying that property.

What you're currently doing is equivalent to the code below:

function return_something() {
    return ['foo', 'bar'];
}

var first_fetch = return_something();
// => ['foo', 'bar']
first_fetch.push('baz'); // => ['foo', 'bar', 'baz']

var second_fetch = return_something(); // => ['foo, 'bar']

Solution

Attach it as a data field instead, perhaps? This way, it will affect the actual object in the DOM, and the jQuery object will carry that data value in subsequent fetches.

jQuery(base).data('showTipTimer', 
  setInterval(function(){tt_locateBase(base);} , 3000));

Then clear with:

clearInterval(jQuery(base).data('showTipTimer'));

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

have you tried this:

   jQuery(base).hover(function() {  
         var idInterval = setInterval( function(){tt_locateBase(base, idInterval);} , 3000 ); 
                         },  

and then

tt_locateBase(base, i){
clearInterval(i);
//code to sidplay tooltip
}

Upvotes: 0

Related Questions