I'm trying to make it so that you can't press an button more than 3 times per second using JavaScript and onclick. Here is my website: http://clickthebutton.herokuapp.com/.
My button's code:
<button id="button" type="button" onclick="loadXMLDoc();">click</button>
My rate-limiter:
function doSomething() {
setTimeout('document.getElementById("button").disabled=false;', 1000);
}
^ not working.
If the button is pressed more than 3 times per second, I'd like to run a function. Please could I have some help with this!
-William
答案 0 :(得分:2)
Here's a really simple example:
// onclick handler
function loadXMLDoc(el) {
// Call rate limiter, passing element
rateLimiter(el);
}
// IIFE - minimizes dem globals
var rateLimiter = (function() {
// Our yummy private variables.
var rate = 0;
var rateLimiter;
var rateLimitTime;
var isRateLimited = false;
// Our returned function that's called when we invoke our IIFE
return function(el) {
// We rate limiting yet? The ! says we ain't.
if (!isRateLimited) {
// INCREMENT!
rate++;
// Set our variable to true, we don't want a bunch of setTimeouts queued up...
isRateLimited = true;
// Runs after a second. Clears the disabled attribute and allows
// for additional rate limiting. Mmmm, throttling......
rateLimiter = setTimeout(function() {
rate = 0;
isRateLimited = false;
el.removeAttribute('disabled');
}, 1000);
}
// OH, hello rate limiting. Let's start!
else {
// Increment and then check our val
if (++rate >= 3) {
// Oh sh*t, we at or over 3. DISABLE!
el.setAttribute('disabled', 'disabled');
}
}
};
}());
Here's a fiddle to demonstrate: http://jsfiddle.net/yja8c034/
(Note: I'm passing this
in the onclick
call)
(Note: This also doesn't require a timer running in the bg resetting a counter)
答案 1 :(得分:2)
Here's my solution, really simple:
HTML:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="post">
<h3> Name :</h3>
<p>
<input type="text" name="username" id="title/">
</p>
<h3>Title :</h3>
<p>
<input type="text" name="title" id="title/">
</p>
<h3>Content :</h3>
<textarea id="content" name="content" rows="20" cols="100"></textarea>
<p>
<br/>
<input type="submit" name="btn_submit" value="Save"/>
</p></form>
</center>
<?php
if (isset($_POST['btn_submit']))
{
$title = $_POST['title'];
$content = $_POST['content'];
if (!isset($title) || empty($title))
{
echo " <h2> check title ! </h2>";
}
else if (!isset($content) || empty($content))
{
echo " <h2> check content ! </h2>";
}
else
{
echo "<p>Success!!! <a href='blogpost.php'>
write other articles ?</a> </p>";
}
}
?>
JS:
<button onclick="rateLimit()">Click me!</button>
Working fiddle:
答案 2 :(得分:1)
you can have a counter that incrememnts everytime your onclick function is fired.
Then, have the function passed to setTimeout
hold an if condition that will check your counter to see if it is 3 or more. If it is, then fire your desired function.
Either way, reset the counter to 0 at the end of the setTimeout, whose delay you can set to 1000 ms.