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);
});
};
}