tags:

views:

35

answers:

2

Hi folks, back again. I just got some help with this snippet...so now I have one final step. This code adds a checkmark to a clicked item 5 seconds after it is clicked. Here's the problem: If three items are clicked in a row quickly, I need to cancel the timeout on the items that are not the last item clicked. The checkbox should only appear if the item is clicked and then five seconds are allowed to elapse. Here's the code:

 $(function() {
 $('li a').click(function() {
      $('li').not('this').css('background-position','left bottom');
      $(this).parent().css('background-position','left top');
       var thetimeout=window.setTimeout($.proxy(function() {
                 $(this).parent().css('background-image','url(images/check.png)');
            }, this)
      ,5000);
 });

});

Here's the demo:www.jontakiff.com/checks

+1  A: 
clearTimeout(thetimeout);

Put that before you set it each time.

Ryley
That's what I thought too, but it isn't working. I added that to the script for the demo.
Johnny
oh wait...I think I see what you're saying...
Johnny
sorry yeah, in the click function...
Ryley
+2  A: 

You have to store the handle of the timeout in a wider scope so that it survives until the next event (i.e. in a scope outside the event handler, so that a closure is created where the variable can survive).

Then you can just use the clearTimeout method if the handle is set:

$(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);
    thetimeout = window.setTimeout($.proxy(function() {
      $(this).parent().css('background-image','url(images/check.png)');
    }, this)
  ,5000);

});
Guffa