Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid allocating functions and use at most one timer per interval in throttleLeadingAndTrailing #5476

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading