Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Debounce!</title>
</head>
<body>
  <p>Click this field:
  <input id="field">
  </p>
  <script>
    // debounce - debounces a function call
    //
    // Usage: var f = debounce([guardTime, ] func);
    //
    // Where `guardTime` is the interval during which to suppress
    // repeated calls, and `func` in the function to call.
    // You use the returned function instead of `func` to get
    // debouncing;
    //
    // Example: Debouncing a jQuery `click` event so if it happens
    // more than once within a second (1,000ms), subsequent ones
    // are ignored:
    //
    //    $("selector").on("click", debounce(1000, function(e) {
    //      // Click occurred, but not within 1000ms of previous
    //    });
    //
    // Both `this` and arguments are passed through.
    function debounce(guardTime, func) {
      var last = 0;
      
      if (typeof guardTime === "function") {
        func = guardTime;
        guardTime = 100;
      }
      if (!guardTime) {
        throw "No function given to debounce";
      }
      if (!func) {
        throw "No func given to debounce";
      }
      
      return function() {
        var now = +new Date();
        if (!last || (now - last) > guardTime) {
          last = now;
          return func.apply(this, arguments);
        }
      };
    }
    
    // Example
    (function() {
      $("#field").on("click focus", debounce(100, function(e) {
        display(+new Date() + ": Got " + e.type);
      }));
      
      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers