Skip to content

Instantly share code, notes, and snippets.

@peacefulseeker
Last active February 17, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peacefulseeker/4f616e486afd044448621bd5aab4a4d6 to your computer and use it in GitHub Desktop.
Save peacefulseeker/4f616e486afd044448621bd5aab4a4d6 to your computer and use it in GitHub Desktop.
JavaScript Throttle Function
//source: https://remysharp.com/2010/07/21/throttling-function-calls
/* Let us work on performance issues while making resource-intensive things */
/* Will wait every `limit` miliseconds until the callback is executed */
function _throttle(fn, threshold, scope) {
threshold || (threshold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshold);
} else {
last = now;
fn.apply(context, args);
}
};
}
// Usage
$(window).on('scroll', _throttle(function() {
if ($(this).scrollTop() > $(this).height()) {
$("#scroll-to-top").addClass('visible');
} else {
$("#scroll-to-top").removeClass('visible');
}
}, 500));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment