Dan Ross
Dan Ross

Reputation: 45

Ignore function if occurred within x seconds

Since people are misunderstanding my wording, I will rewrite it, I want "with the following code below" to ignore the function which i have commented on below in my jquery if it happened in the last "X" seconds. Here is my code.

EDIT:: Please write answers in reference to this, example. "the script ignores the change in class and the delay wont work" http://www.w3schools.com/code/tryit.asp?filename=FBC4LK96GO6H

Sorry for confusing everyone including myself.

Upvotes: 0

Views: 295

Answers (2)

Karol Łuckiewicz
Karol Łuckiewicz

Reputation: 152

Edited due to author's post update.

You can create custon event. By this function you will define: "delayedClick" event on the selected objects.

function delayedClickable(selector, delayTime){
  $(document).ready(function(){
    $(selector).each(function () {
      var lastTimeFired = 0;
      $(this).click(function(){
        if(Date.now() - delayTime > lastTimeFired) {
          lastTimeFired = Date.now();
          $(this).trigger('delayedClick');
        }
      });
    });
  });
}

Remeber that you should define delayTime and this event on selected elements by:

var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);

And then just use your event on elements. For example click event can be used in that way:

$element.on('click', function () {
  // ...
});

And your custom delayedClick event should be used in that way:

$element.on('delayedEvent', function () {
  // ...
});

Full example: http://www.w3schools.com/code/tryit.asp?filename=FBC56VJ9JCA5


@UPDATE I've found some another tricky way to keep using click function and makes it works as expected:

function delayedClickable(selector, delayTime){
  $(document).ready(function(){
    $(selector).each(function () {
      var scope = this;
      $(this).click(function(){
        scope.style.pointerEvents = 'none';
        setTimeout(function () {
          scope.style.pointerEvents = 'auto';
        }, delayTime);
      });
    });
  });
}

And then

var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);

That's all.

The key of second way is that we are disabling any pointer event on element when clicked and then after timeout we're turning these events back to work. https://developer.mozilla.org/en/docs/Web/CSS/pointer-events

And full example: http://www.w3schools.com/code/tryit.asp?filename=FBC678H21H5F

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

Can use setTimeout() to change a flag variable and a conditional to check flag in the event handler

var allowClick = true,
    delaySeconds = 5;
$(".element1").click(function(){
   if(!allowClick){
      return; // do nothing and don't proceed
   }
   allowClick = false;
   setTimeout(function(){
      allowClick = true;
   }, delaySeconds * 1000 );

   // other element operations
})

Upvotes: 1

Related Questions