JSFiddle - React, Tailwind, and code Playground

by mrmartineau

HTML

<html>
  <head>
  </head>
  <body>
    <h1>Move your mouse around (and stop for a bit too to let debounce do it's thing).</h1>
    <br>  
    <div class="status">
        <div id="unlimited">
            <div>Unlimited calls:</div>
            <div>0</div>
        </div>
        <div id="debounce">
            <div>Debounced calls:</div>
            <div>0</div>
        </div>
        <div id="throttle">
            <div>Throttled calls:</div>
            <div>0</div>
        </div>
    </div>
  </body>
</html>

CSS

body { font-family:"Verdana"; font-size: 14px; }
h1 { font-size: 18px; font-weight: bold; }
.status div div { width: 160px; display: inline-block; }
.status div div:last-child { width: 40px; text-align: right; }

JavaScript

/**
 * debounce
 * @param {integer} milliseconds This param indicates the number of milliseconds
 *     to wait after the last call before calling the original function .
 * @return {function} This returns a function that when called will wait the
 *     indicated number of milliseconds after the last call before
 *     calling the original function.
 */
Function.prototype.debounce = function (milliseconds) {
    var baseFunction = this,
        timer = null,
        wait = milliseconds;

    return function () {
        var self = this,
            args = arguments;

        function complete() {
            baseFunction.apply(self, args);
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(complete, wait);
    };
};

/**
* throttle
* @param {integer} milliseconds This param indicates the number of milliseconds
*     to wait between calls before calling the original function.
* @return {function} This returns a function that when called will wait the
*     indicated number of milliseconds between calls before
*     calling the original function.
*/
Function.prototype.throttle = function (milliseconds) {
    var baseFunction = this,
        lastEventTimestamp = null,
        limit = milliseconds;

    return function () {
        var self = this,
            args = arguments,
            now = Date.now();

        if (!lastEventTimestamp || now - lastEventTimestamp >= limit) {
            lastEventTimestamp = now;
            baseFunction.apply(self, args);
        }
    };
};


/* Test code */

var unlimitedCalls = 0,
    debounceCalls = 0,
    throttleCalls = 0;

$(document).bind('mousemove', function(e) {
    $("#unlimited").children().last().text(unlimitedCalls++);
}); // no limit applied

$(document).bind('mousemove', function(e) {
    $("#debounce").children().last().text(debounceCalls++);
}.debounce(150)); // debounce with a 150 millisecond limit

$(document).bind('mousemove',...