Skip to content

Commit

Permalink
Avoid allocating functions and use at most one timer per interval in …
Browse files Browse the repository at this point in the history
…throttleLeadingAndTrailing (#5476)

Co-authored-by: Noeri Huisman <mrxz@users.noreply.github.com>
  • Loading branch information
mrxz and mrxz committed Mar 18, 2024
1 parent 1880be1 commit fe238e7
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,20 +89,30 @@ module.exports.throttleLeadingAndTrailing = function (functionToThrottle, minimu
if (optionalContext) {
functionToThrottle = functionToThrottle.bind(optionalContext);
}
var args;
var timerExpired = function () {
// Reached end of interval, call function
lastTime = Date.now();
functionToThrottle.apply(this, args);
deferTimer = undefined;
};

return function () {
var time = Date.now();
var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
var args = arguments;
if (typeof lastTime === 'undefined' || sinceLastTime >= minimumInterval) {
if (sinceLastTime >= minimumInterval) {
// Outside of minimum interval, call throttled function.
// Clear any pending timer as timeout imprecisions could otherwise cause two calls
// for the same interval.
clearTimeout(deferTimer);
deferTimer = undefined;
lastTime = time;
functionToThrottle.apply(null, args);
functionToThrottle.apply(null, arguments);
} else {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
lastTime = Date.now();
functionToThrottle.apply(this, args);
}, minimumInterval - sinceLastTime);
// Inside minimum interval, create timer if needed.
deferTimer = deferTimer || setTimeout(timerExpired, minimumInterval - sinceLastTime);
// Update args for when timer expires.
args = arguments;
}
};
};
Expand Down

0 comments on commit fe238e7

Please sign in to comment.