Manual (non Underscore.js) JavaScript demonstration of protecting against rapid-fire button presses

Below is a demonstration of how JavaScript timeouts can be used to protect against rapid-fire requests (such as when user clicks buttons as fast as they can for fun). Try out this page now, or view it as a JSFiddle.

(This is a manual version of Underscore.jsdebounce function–you should use Underscore in your projects. This is only intended for showing how debounce conceptually works. Here is an example use of debounce in my Django AJAX/JQuery tutorial.)

<!DOCTYPE html>
<html lang="en">
   <title>Demo: Preventing rapid-fire requests</title>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <meta name="viewport" content="width=device-width"/>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
   </head>
</html>

<body>
   <h2>Demo: Preventing rapid-fire requests</h2>

   <p>Click on this button as fast as you can. The first click is recognized. All others within the next two seconds are ignored.</p>

   <p><button>Go</button></p>

   <ul>
   </ul>

   <script language="javascript">
      var counter = 1;
      function onClick() {
         //The event listener is no longer attached.

         var millisecondsToIgnore = 2000;  //Two seconds

         $("ul").prepend('<li>' + counter + ': Disabled for ' + millisecondsToIgnore + ' milliseconds</li>');

         //Execute the anonymous function after pausing.
         setTimeout(function() {
            $("ul").prepend('<li>' + counter++ + ': Re-enabled</li>');

            //Again: "one"
            $(this).one('click', onClick);
         }, millisecondsToIgnore);
      }

      /*
         Attach the initial event listener on page-load. THIS MUST BE
         BELOW THE BUTTON ITSELF.

         The "one" function attaches the listener to the element and
         immediately unattaches it when the event is triggered.

         See http://api.jquery.com/one/
       */
      $('button').one('click', onClick);
   </script>
</body></html>
Advertisements

One thought on “Manual (non Underscore.js) JavaScript demonstration of protecting against rapid-fire button presses

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s