Last active
February 17, 2018 15:38
-
-
Save peacefulseeker/30aad798fff281cea08fba8f29a73eb0 to your computer and use it in GitHub Desktop.
JavaScript Debounce 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 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