Respond to an event only once every 5 seconds

I am trying to run a function using setInterval() and click. I want to run somefunction() only once every five seconds when I click.

Here is my code:

 function somefunction(){ // do something } setInterval(function(){ $('#division').one("click",function(){ somefunction(); }); }, 5000); 

The problem here is that the setInterval() event is in the queue and after some 30 seconds says somefunction() ; works up to 6 times (in 6 clicks).

But I want it to start only once and wait for the next 5 seconds.

I tried .stop() , .dequeue() and .clearqueue() , although nothing worked.

Thank you for your help!

+4
source share
2 answers

How to ignore every click that was less than 5 seconds ago?

 function somefunction() { /* do something */ } $('#division').on("click", function () { var lastClicked = $(this).data("lastClicked") || 0; if (new Date() - lastClicked >= 5000) { $(this).data("lastClicked", new Date()); somefunction(); } }); 

Alternatively, plan the click according to the last, ignore all clicks while the action is planned:

 function somefunction() { /* do something */ } $('#division').on("click", function () { var $this = $(this), lastClicked = $this.data("lastClicked") || 0, isScheduled = $this.is(".scheduled"); if (!isScheduled) { $this.addClass("scheduled"); setTimeout(function () { somefunction() $this.removeClass("scheduled").data("lastClicked", new Date()); }, Math.max(0, 5000 - (new Date() - lastClicked))); } }); 

See: http://jsfiddle.net/Tomalak/ZXfMQ/1/

+4
source

If you agree to using underscore.js , I recommend using its debounce :

 $('#division').on('click', _.debounce(someFunction, 5000, true)); 

Also, here is a great article on how debouncing works .

If you want to flip your own debouncing, it's that simple:

 $('#division').on('click', (function(func, wait, immediate) { var timeout, result; return function() { var self, args, callNow; function later () { timeout = null; if (!immediate) result = func.apply(self, args); } self = this; args = arguments; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { result = func.apply(self, args); } return result; }; }(someFunction, 5000, true)))); 

... just kidding, it just emphasizes the debounce inline function.

+4
source

All Articles