Created
February 16, 2016 10:19
-
-
Save ahallora/ef7d6947232b5bc0e37d to your computer and use it in GitHub Desktop.
A simple Click Rate Limiter / Debouncer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looke at me spreading knowledge... like a boss. 😄