Skip to content

Instantly share code, notes, and snippets.

@ahallora
Created February 16, 2016 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahallora/ef7d6947232b5bc0e37d to your computer and use it in GitHub Desktop.
Save ahallora/ef7d6947232b5bc0e37d to your computer and use it in GitHub Desktop.
A simple Click Rate Limiter / Debouncer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<ul id="list"></ul>
<button id="thebutton">Try me</button>
<script>
$(document).on('ready', function () {
$('#thebutton').on('touchstart click touchend', someFunction);
});
function someFunction() {
/* Click Rate Limiter start */
var actionIdentifier = 'savePressedId';
var noRateLimit = clickRateLimiter(actionIdentifier, 2500);
if (!noRateLimit) return false; // function is quarntined - prevent it from executing
/* Click Rate Limiter end */
/* do your business logic as usual */
$('#list').append('<li>' + new Date() + '</li>');
}
/* Created by Anders Holm-Jensen, allora.dk - License: MIT */
var rateLimitArray = [];
function clickRateLimiter(funcId, limit) {
var go = true;
var arrayId = -1;
var now = Date.now();
var obj = { 'id': funcId, 'timestamp': now };
$(rateLimitArray).each(function (i, item) {
if (item.id === funcId) {
arrayId = i;
var max = item.timestamp + limit;
if (max - now > 0) {
// halt it
console.log(funcId + ' blocked by clickRateLimiter. (' + (max - now) + ' time left)');
go = false;
}
}
});
if (go) {
// if not returned yet go ahead
if (arrayId === -1) {
rateLimitArray.push(obj);
} else {
rateLimitArray.splice(arrayId, 1, obj); // replace in CRL array
}
// run function
console.log(funcId + ' executed with clickRateLimiter');
}
return go;
}
</script>
</body>
</html>
@ahallora
Copy link
Author

Looke at me spreading knowledge... like a boss. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment