Throttle test (v2)

Revision 2 of this benchmark created on


Setup

let lastInline = 0;
let DELAY = 250;

const work = function() {
}

const throttle = function(delay, callback) {
  let last = 0;
  const fn = (...args) => {
    const now = performance.now();
    if (now > last + delay) {
      // Invoke the callback now if enough time has passed.
      last = now;
      callback(...args);
    }
  };
  return fn;
}

const throttleEnsure = function(delay, callback) {
  let last = 0;
  let handle = undefined;
  const fn = (...args) => {
    // Cancel any scheduled invocation.
    if (handle) {
      clearTimeout(handle);
      handle = undefined;    	
    }

    const now = performance.now();
    if (now > last + delay) {
      // Invoke the callback now if enough time has passed.
      last = now;
      callback(...args);
    } else {
      // Otherwise schedule it to be invoked as soon as possible when the delay expires.
      handle = setTimeout(() => fn(...args), delay - (now - last));
    }
  };
  return fn;
}

const throttleWork = throttle(DELAY, () => work());

const throttleEnsureWork = throttleEnsure(DELAY, () => work());

Test runner

Ready to run.

Testing in
TestOps/sec
Inline Throttle
const now = performance.now();
if( now > lastInline + DELAY) {
	lastInline = now;
	work();
}
ready
Wrapped Throttle
throttleWork();
ready
Wrapped Throttle with Scheduling
throttleEnsureWork();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.