简体   繁体   中英

How can I delay the submission of a form?

I have a web site that uses submit buttons to send commands to a remote microprocessor. If a user clicks the submit button too many times in a short amount of time, the remote microprocessor and software will crash. I thought I could add a one-second delay between each "submit" button press so it will not crash. Here is what I have for the submit button.

<form name="test" action="http://mydomain.dyndns.org/?8" target="results" method="POST">
<input type="submit" value=" ← Move Left " />
</form>

I thought I could use something like onSubmit="setTimeout (1000)" in the form, but it doesn't seem to be working. What am I doing wrong?

Example:

<form name="test" action="http://mydomain.dyndns.org/?8" target="results" method="POST" onSubmit="setTimeout (1000)">
    <input type="submit" value=" ← Move Left " />
</form>

You'll have to actually write code to queue the requests and send them to the microprocessor at whatever rate the microprocessor can safely accept. You need to do this on the server side, not on the client side.

A back-end solution is preferable, but if you want to do it client-side as well (or instead):

If your onsubmit returns false it will stop submission.

I'd be inclined to solve this by:

  1. Temporarily disabling the button for a second so that the user can't submit again quickly, and/or
  2. Ignoring subsequent attempts to submit unless at least a second has passed.

I would not bother trying to queue up all the submissions and space them out, because the user could click the button lots of times.

So, the following ignores extra attempts to submit made within a second and disables the submit button. Why do both? If the form has fields in it the user could submit by pressing the Enter key.

<form name="test" action="http://mydomain.dyndns.org/?8" target="results"
      method="POST" onSubmit="return testSubmit();">
   <input id="submitButton" type="submit" value=" ← Move Left " />
</form> 

<script>
   var allowSubmit = true;

   function testSubmit() {
      if (!allowSubmit)
         return false;

      allowSubmit = false;
      document.getElementById("submitButton").disabled = true;

      setTimeout(function() {
                    allowSubmit = true;
                    document.getElementById("submitButton").disabled = false;
                 }, 1000);

      return true;
   }
</script>

Note this code: onSubmit="return testSubmit();" - you need the "return" in there or the value that comes back from testSubmit() is thrown away and submission will not be prevented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM