How To Make a Debounced Throttle in JavaScript
TL;DR
Neither debouncers or throttles do what I want by themselves. Throttles catch initial changes but miss the last one. Debouncers skip the first on in favor of catching the last.
This code combines them to get the effect I'm looking form. (An example demonstration and more details are further below.)
TODO: put in note about requestAnimationFrame()
JavaScript
const debouncedThrottle = ;
Do It Live
This example uses the code above.
Value 1: Waiting
Value 2: Waiting
Throttle By Itself Isn't Good
It picks up the changes immediately but missing the last ones unless it's at the exact right millisecond.
Output
Waiting
HTML
Waiting
Throttle Only Slider
Debounce By Itself Isn't Good
This doesn't update the value until you've stopped moving the slider for 1 second.
JavaScript
const debouceOnly = ;
Output
Waiting
HTML
Waiting
Debug Only Slider
/*
function throttle(func, timeFrame) {
var lastTime = 0;
return function (...args) {
var now = new Date();
if (now - lastTime >= timeFrame) {
func(...args);
lastTime = now;
}
};
}
/*
/*
debounce(callback, wait) {
const localThis = this;
console.log("asdf");
let timeoutId = null;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => {
//this.doUpdate(this);
// callback.apply(localThis, args);
}, wait);
};
}
queueUpdate(event) {
this.debounce(this.doUpdate, 2000);
}
*/
/*
*/
//let doUpdateId = null;
// this.doUpdateId = "asdf";
//window.clearTimeout(doUpdateId);
//console.log(this.doUpdateId);
// console.log("----");
//console.log(this.slider.value);
-- end of line --