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=""></script>
<style type="text/css">
#id1 {min-height: 1600px;}
<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);

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


Click here to write/view comments