Javascript onscroll event handler with throttling

Javascript onscroll event handler is called on every onscroll event. At times we want to ensure that it is not called again before a certain minimum duration. Utility library underscopre (lodash) function throttle can be used for this purpose.

Usage of underscore throttle:

// wait is in milliseconds
throttle_.throttle(function, wait, [options])


Example code where we use throttle function in scroll event handler with 1 second duration.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<style type="text/css">
#id1 {min-height: 1600px;}
</style>
<div id="id1">==Scroll this document==<br/></div>

<script type="text/javascript">
var handle_scroll = function (e) {
  document.querySelector("#id1").innerHTML += "time=" + new Date().getTime() + "<br/>";
}
document.onscroll = _.throttle(handle_scroll, 1000);
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments