Reputation: 21
I have already gotten some good help on a piece of code I'm struggling with. Hopefully someone can help me again. I have code which shows a checkmark next to an item 5 seconds after it's clicked. The problem: I need to cancel the checkmark popping up if the user is rapidly clicking links. Here's the demo:
Here's the code. I've gotten some help on this one from a few folks, but the Timeout still isn't working:
$(function() {
var thetimeout=null;
$('li a').click(function() {
$('li').not('this').css('background-position','left bottom');
$(this).parent().css('background-position','left top');
if(thetimeout!=null) {
window.clearTimeout(thetimeout);
}
var thetimeout=window.setTimeout($.proxy(function() {
$(this).parent().css('background-image','url(images/check.png)');
}, this)
,5000);
});
});
The clearTimeout should cancel the Timeout for all unclicked elements but it isn't working...any ideas?
Upvotes: 0
Views: 233
Reputation: 48620
The timeout you have set exists locally inside the click event - therefor in each click event exists it's own timeout.
Move var thetimeout
to before your $('li').click
and then inside the click event just use thetimeout=
(as having another var here defines a new variable in the local scope, instead of using the prior one).
Additionally depending on your use case, you may want to check to see if the timeout doesn't already exist if ( !thetimeout )
before setting the new one, as well as always after calling clearTimeout(thetimeout)
you should do thetimeout = null
as otherwise the variable may still have a value.
As the above recommendations may leave room for confusion, here is the attached code with the recommendations applied:
$(function() {
// Define our Timeout
var thetimeout=null,
clearTheTimeout = function(){
if ( thetimeout ) {
window.clearTimeout(thetimeout);
}
thetimeout = null;
};
// Do our Click
$('li a').click(function() {
$('li').not('this').css('background-position','left bottom');
$(this).parent().css('background-position','left top');
// Clear the Timeout
clearTheTimeout();
// Set the Timeout
thetimeout = window.setTimeout(
$.proxy(function(){
$(this).parent().css('background-image','url(images/check.png)');
clearTheTimeout();
},this)
,5000);
});
});
Upvotes: 1