1

I have an anchor which is using jQuery .click event to start a few functions.

jQuery(document).ready(function(){  
    jQuery('a.slide_circ').click(function(){ 
        do_all_functions();
        return false; 
    });
});

This is the code in short.. Its working as it needs to, every click on anchor class slide_circ start do_all_functions.

But I have a problem there. If user make double clicks they run 2 times or more the functions... And the how idea go to hell.

I think that I need to disable the double click some way or to set timeout on my function so its not running each time. Can anyone help me ?

Svetoslav
  • 4,686
  • 2
  • 28
  • 43

3 Answers3

5

Use the .data method to assign the state to the element. Then, use setTimeout to reset the state:

jQuery(document).ready(function() {
    jQuery('a.slide_circ').click(function() { 
        var $this = jQuery(this);
        if ($this.data('activated')) return false;  // Pending, return

        $this.data('activated', true);
        setTimeout(function() {
            $this.data('activated', false)
        }, 500); // Freeze for 500ms

        do_all_functions();
        return false; 
    });
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

A few ways to do it, but one way is:

jQuery(document).ready(function(){ 
    var do_all_functions_running = false; 
    jQuery('a.slide_circ').click(function(){
        if (!do_all_functions_running) { 
            do_all_functions_running = true;
            do_all_functions();
            do_all_functions_running = false;
        }
        return false;   
    });  
});

Not perfect, but it'll work.

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
  • 1
    this won't work, you're setting the click event when you use .click(), not executing the function. – nicosantangelo Feb 19 '12 at 15:16
  • This method is equivalent to `.unbind('click')`, because the function will now only run once, and never again. – Rob W Feb 19 '12 at 15:23
  • Re-reading the question (or rather the comments), he wants it to run for as many times as it is clicked. So ignore my attempt... – Adrian Lynch Feb 19 '12 at 15:25
0

You can check the last date of the run, and cancel if it was less than half a second ago:

jQuery(document).ready(function() {
    jQuery('a.slide_circ').each(function() {
        var lastRun = null;

        $(this).click(function() {
            if(lastRun && new Date() - lastRun < 500) {
                // Less than 500ms; ignore.
                return false;
            }

            // Set the last run:
            lastRun = new Date().getTime();

            // Continue:
            do_all_functions();
            return false; 
        });
    });
});

It has the advantage of being a little more efficient.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • It doesn't work with more than one `a.slide_circ` element. They'll conflict with each other. – Rob W Feb 19 '12 at 15:21