Throttle Scroll Event

Throttle execution of the Scroll Event to prevent performance issues

by sjmcpherson

HTML

<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<div id="navbar-border"></div>

CSS

body {
  height: 1000px;
}

JavaScript

var navbar = $('#navbar-border');
    var threshold = 100; // in milliseconds

    function borderControl() {
      console.log("run");
      var scroll = $(window).scrollTop();
      if (scroll >= 40) {
        navbar.addClass("navbar-border");
      } else {
        navbar.removeClass("navbar-border");
      }
    }

    function setScrollTimer() {
      unbindScroll();
      scrollTimer = window.setTimeout(function() {
        bindScroll()
      }, threshold);
    }

    function unbindScroll() {
      $(window).unbind("scroll");
    }

    function bindScroll() {
      $(window).scroll(function(e) {
        setScrollTimer();
        borderControl();
      });
    }
    bindScroll();