ClearTimeout not working

SetTimeout does not work for the following 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 item is registered for both click events and double-click. To cancel the click event on doubleclick, the setTimeout function is registered. I get the Ineger timer id using the double click method, but clearTimeout does not cancel the function being executed. I do not get an error. Thanks in advance.

+3
source share
1 answer

You cannot distinguish between a click and a double click, so each double click also triggers two separate click events. Each of these click events also fires setTimeout, but overwrites the value .data('clickTimer').


: http://jsfiddle.net/mattball/Az6zY/


click. :

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

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

+6

All Articles