开发者

how to use clearTimeout to make the page work

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() {
开发者_如何学Python      $('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


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);

});


clearTimeout(thetimeout);

Put that before you set it each time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜