0

I have some sliders, that when changed runs a fairly heavy computation function. This results in some heavy stuttering when dragging the slider, and a generally bad experience overall.

So my idea was to use debouncing, so that if the last computation have not finished, it will be discarded and a new one with the latest input value will start instead.

The problem is that my debounce function only works if the computation takes less time than the animation frame request, and I don't know how I would make it cancel the currently running operation if it's not finished when the next value is being set.

function debounce(callback) {
  let handle;

  return function debounced(...args) {
    return new Promise(resolve => {
      if (handle !== undefined) {
        cancelAnimationFrame(handle);
      }

      const delayed = () => {
        resolve(callback.apply(this, args));
        handle = undefined;
      };

      handle = requestAnimationFrame(delayed);
    });
  };
}
Glinkis
  • 83
  • 6
  • I think it would be useful to know what requestAnimationFrame actually does, and the same goes for cancelAnimationFrame. That will give a better insight in how you have thought this would work conceptually. The code you have presented now doesn't seem to be doing anything out of the ordinary. Only import thing I find missing in your debounce functionality is some sort of timed delay. But I guess you have that inside your requestAnimationFrame function. – enf0rcer Apr 16 '18 at 13:00
  • @enf0rcer - requstAnimationFrame & cancelAnimationFrame are part of the dom api: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame – Glinkis Apr 16 '18 at 13:07

0 Answers0