3gwebtrain
3gwebtrain

Reputation: 15303

set/clear interval issue

HI,

i am using the following code to show a link which is inside the li element. the constrain is, once the mouse enter into li element, and if it's stay inside 3sec, then it need to show. once i leave from li element, immateriality it should hide. for this, i am using :

var showTimeOut;
var thisElement

$('.user-list li').live('mouseover',function(){

    thisElement = $(this).children('a.copier-link');

    showTimeOut = setInterval(function(){
        thisElement.css({'display':'block'});
    },3000);
})

$('.user-list li').live('mouseleave',function(){
    clearInterval(showTimeOut);
    thisElement.hide();
})

It's work fine. But the problem is, while i cross the li element with just a second, even the interval is calling, and showing the link. but i need to show only, if i stay inside 3sec and it need to hide there after, again i stay back 3sec.

anything wrong with my code?, else any one give me the best suggestion?

Thanks.

Upvotes: 0

Views: 2375

Answers (2)

Andy E
Andy E

Reputation: 344567

This is only a guess, but it could be to do with your use of mouseover instead of mouseenter. mouseover can fire multiple times if you have child elements within the li element, which would set the interval multiple times and overwriting the value of the showTimeout variable. This means when mouseleave fires, only the last interval to be set would be cleared.

Try changing your mouseover event to mouseenter instead. I would also consider changing setInterval to setTimeout, as setInterval will set a timer to run a function recurring every 3 seconds here, unnecessarily applying the .css() again. setTimeout would only call the function once.


Another idea would be to always call clearTimeout before setTimeout, then you know that two timers can't run simultaneously:

clearTimeout(showTimeout);
showTimeOut = setTimeout(function(){
    thisElement.css({'display':'block'});
},3000);    

Upvotes: 1

Alex
Alex

Reputation: 12433

Maybe the hoverIntent jQuery Plug-In is what you're looking for?

hoverIntent is a plug-in that attempts to determine the user's intent... like a crystal ball, only with mouse movement! It works like (and was derived from) jQuery's built-in hover. However, instead of immediately calling the onMouseOver function, it waits until the user's mouse slows down enough before making the call.

Upvotes: 0

Related Questions