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/30aad798fff281cea08fba8f29a73eb0 to your computer and use it in GitHub Desktop.
Save peacefulseeker/30aad798fff281cea08fba8f29a73eb0 to your computer and use it in GitHub Desktop.
JavaScript Debounce Function
//source: https://remysharp.com/2010/07/21/throttling-function-calls
/* Let us work on performance issues while making resource-intensive things */
/* Will wait until event is not stopped and wait param is finished, then the callback will be fired */
function _debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Usage:
$(window).on('scroll', _debounce(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