3

SetTimeout is not working for the follwing code:

   $("#clkDblClk").click(function(){           
       var clickTimer=setTimeout(function(){
            //Some code to execute
          },1000); 
        $(this).data("clickTimer",clickTimer);
     });
     $("#clkDblClk").dblclick(function(){
       var clickTimer=$(this).data("clickTimer");
       clearTimeout(clickTimer);
       //Some ajaxRequest
     });

The element is registered for both click and double click events.To cancel out click event on doubleclick, setTimeout function is registered.I get the Ineger timer id in double click method, but clearTimeout is not cancelling out the function to execute. I'm not getting the error. Thanks in advance.

Avneesh Raghav
  • 319
  • 2
  • 11
  • 2
    See http://stackoverflow.com/questions/1067464/need-to-cancel-click-mouseup-events-when-double-click-event-detected –  Jul 01 '11 at 14:32

1 Answers1

6

There is no way to distinguish between a click and a double-click, so every double-click also triggers two separate click events. Each of those click events is also starting the setTimeout, but it overwrites the .data('clickTimer') value.


Here's the proof: http://jsfiddle.net/mattball/Az6zY/


One solution is to debounce the click event. Really simple implementation:

var DATA_KEY = 'clickTimer';

$('#clkDblClk').click(function()
{
    var $this = $(this);

    if ($this.data(DATA_KEY)) return;

    var clickTimer = setTimeout(function()
    {
        // do other stuff

        $this.removeData(DATA_KEY);
    }, 1000);

    $this.data(DATA_KEY, clickTimer);
})
.dblclick(function()
{
    var $this = $(this);

    var clickTimer = $this.data(DATA_KEY);
    clearTimeout(clickTimer);

    $this.removeData(DATA_KEY);
});

Demo: http://jsfiddle.net/mattball/B5MSw/

Matt Ball
  • 354,903
  • 100
  • 647
  • 710