Adding a delay before calling function in .hover() callback
I'm trying to add a small delay in the .hover() callback before running further code. I also need to stop the timer if it exists when you hover another elem that triggers the same .hover() func. I currently have it working but it is not pretty, I'm assigning a timer to a global and sure there must be a better way to do this.
Here is what I have:
PACKAGES.activity_icons.hover(function() {
// If a timer exists kill it here becuase we don't want the
// functions in the timer called if we are hovering on another icon
if(typeof image_restore_timer != 'undefined')
{
clearTimeout(image_restore_timer);
}
// Only swap image if icon has a class
if($(this).attr('class') !== '')
{
$(this).closest('.package').find('.left_wrap > img').hide();
// Show the image with the same class as the icon we hovered
$(this).closest('.package').find('.le开发者_如何学运维ft_wrap img.'+$(this).attr('class')).show();
}
}, function() {
var this_ref = $(this);
// Store timer in a global and restore images after a pause
image_restore_timer = setTimeout(function() {
(function(el) {
el.closest('.package').find('.left_wrap img.'+this_ref.attr('class')).hide();
el.closest('.package').find('.left_wrap > img:eq(0)').fadeIn('slow');
})(this_ref)
}, 1000);
});
You can store a timer per element (instead of a global one) using $.data()
, like this:
PACKAGES.activity_icons.hover(function() {
clearTimeout($.data(this, 'timer'));
if(this.className === '') return;
$(this).closest('.package').find('.left_wrap > img').hide()
.end().find('.left_wrap img.'+ this.className).show();
}, function() {
var el = this;
$.data(this, 'timer', setTimeout(function() {
$(el).closest('.package').find('.left_wrap img.' + el.className).hide()
.end().find('.left_wrap > img:eq(0)').fadeIn('slow');
}, 1000));
});
The other changes are just some optimizations, the main idea is store the timer using $.data()
and clear that same timer. Also, clearTimeout()
doesn't error with a null or already-run timer, so you can just call it with no check.
You're looking for the hoverIntent plugin.
精彩评论