On the https://javascript.info/call-apply-decorators there is the solution for the Throttling decorator task. I've modified the code to get rid of 'sevedThis' and it works perfectly without it (even with object methods). Could anybody give a real reason to use 'sevedThis' variable in this case and call 'wrapper.apply(savedThis, savedArgs)' instead of 'wrapper(...savedArgs)'?
Original code:
function throttle(func, ms) {
let isThrottled = false,
savedArgs,
savedThis;
function wrapper() {
if (isThrottled) { // (2)
savedArgs = arguments;
savedThis = this;
return;
}
isThrottled = true;
func.apply(this, arguments); // (1)
setTimeout(function() {
isThrottled = false; // (3)
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
Code without 'savedThis':
function throttle(func, ms) {
let isThrottled = false,
savedArgs;
function wrapper() {
if (isThrottled) {
// (2)
savedArgs = arguments;
return;
}
func.apply(this, arguments); // (1)
isThrottled = true;
setTimeout(function () {
isThrottled = false; // (3)
if (savedArgs) {
wrapper(...savedArgs);
savedArgs = null;
}
}, ms);
}
return wrapper;
}