Last active
May 20, 2022 16:58
-
-
Save msssk/b720a8bddf2ba595347820ac387751ce to your computer and use it in GitHub Desktop.
Throttle with trailing call preservation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a typical throttle implementation with the difference that it doesn't discard | |
// the final invocation - instead it runs it at the next valid timeslice. | |
throttleBoss: function(callback, delay) { | |
var ready = true, | |
args = null; | |
return function throttled() { | |
var context = this; | |
if (ready) { | |
ready = false; | |
setTimeout(function() { | |
ready = true; | |
if (args) { | |
throttled.apply(context); | |
} | |
}, delay); | |
if (args) { | |
callback.apply(this, args); | |
args = null; | |
} else { | |
callback.apply(this, arguments); | |
} | |
} else { | |
args = arguments; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Goal: a throttle method for rapid event handlers, such as
mousemove
andscroll
.Presumed desirable traits:
throttle
Trailing invocations are discarded
throttleAfter
Initial invocation and trailing invocations are discarded
throttleBoss
Final trailing invocation executes at next eligibile timeslice