Alvaro Parra
Alvaro Parra

Reputation: 805

timeout between clicks jquery

i have the following code to count clicks on a div

$('.ps-next').click(function () {
    setTimeout($('#currentImage').html(parseInt($('#currentImage').html(), 10) - 1), 10000);
});

$('.ps-prev').click(function () {
    setTimeout($('#currentImage').html(parseInt($('#currentImage').html(), 10) + 1), 10000);
});

i would like to count clicks but i want to put a delay of 1 second between clicks. or at least not count fast clicks can anyone help me.

Upvotes: 0

Views: 211

Answers (2)

Bill Criswell
Bill Criswell

Reputation: 32941

I use a slightly different approach than most here.

The event object has a timeStamp property, so I compare that to the previous timestamp. Here's how I'd approach the situation...

var lastClick, 
    $count = $('.count');

$('.stepper').on('click', function(e){

  // If we have a lastClick value or the current timeStamp
  // minus lastClick is greater than 1000 ( 1 second ), go to work.
  if ( !lastClick || lastClick && e.timeStamp - lastClick > 1000 ) {

    var $stepper = $(this);

    $count.text(function(i, txt){
      var current = +txt;
      return current + ( $stepper.is('.up') ? 1 : -1 );
    });

    lastClick = e.timeStamp;
  }

});

Along with this HTML.

<div class="stepper up">Up</div>
<div class="count">5</div>
<div class="stepper down">Down</div>

Here is a quick demo: http://jsbin.com/iruXisOn/1/edit

Upvotes: 1

HDT
HDT

Reputation: 2047

you can use this jquery plugin

(function ($) { 
    $.fn.oneClickPerTime = function (callback,timeDelay) {
        var __this = this;
        flagOneClick = 1;
        return this.each(function () {
            $(__this).click(function() {
                if (flagOneClick==0)
                    return;
                flagOneClick = 0;
                setTimeout(function() {
                    flagOneClick = 1;
                },timeDelay);
                callback(this);
            });
        });
    } 
})(jQuery);

then call function and must define the timeout, ex: 1000 (1 second)

$('.ps-prev').oneClickPerTime(function(){
     //callback
},1000);

Upvotes: 1

Related Questions