Last active
February 17, 2018 15:38
-
-
Save peacefulseeker/4f616e486afd044448621bd5aab4a4d6 to your computer and use it in GitHub Desktop.
JavaScript Throttle Function
This file contains hidden or 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
//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