JSFiddle - React, Tailwind, and code Playground
HTML
<div id="console"></div>
JavaScript
// limit a function to only firing once every XX ms
var throttle = function(fn, delay) {
var last = 0,
timeout, args, context;
delay || (delay = 100);
return function() {
// we subtract the delay to prevent double executions
var now = +new Date,
elapsed = (now - last - delay);
args = arguments, context = this;
function exec() {
// remove any existing delayed execution
timeout && (timeout = clearTimeout(timeout));
fn.apply(context, args);
last = now;
}
// execute the function now
if (elapsed > delay) exec();
// add delayed execution (this could execute a few ms later than the delay)
else if (!timeout) timeout = setTimeout(exec, delay);
};
};
// Better throttle: the proposed _.paced() method: https://github.com/documentcloud/underscore/pull/266
var paced = function(func, wait) {
var ran = false;
return function() {
if (!ran) {
ran = true;
setTimeout(function() {
ran = false;
}, wait);
return func.apply(this, arguments);
}
};
};
var throttleCount = 0;
var throttlef = throttle(function() {
++throttleCount;
}, 100);
var pacedCount = 0;
var pacedf = paced(function() {
++pacedCount;
}, 100);
pacedf();
pacedf();
throttlef();
throttlef();
setTimeout(function() {
$("#console").html("Proposed throttle: 2 calls were made, and " + throttleCount + " of them made it through to the underlying system" + "<br />" + "Proposed paced: 2 calls were made, and " + pacedCount + " of them made it through to the underlying system");
}, 1000);