title: Limiting Scroll and Resize events
body: <p>This is a general question about a problem I run into often, where I need something to happen at a certain screen width, or scrollTop position, so I end up triggering events for the entire scroll or resize event. This seems really unnecessary and hurts performance. I am wondering what steps I can take to limit calling code written inside scroll or resize events so that I am only triggering these events when I need them.</p>
  
  <p>In the example below I just want the background color to change at a certain scrollTop offset, but since its wrapped in a scroll event, it gets trigged for every pixel. </p>
  
  <p>I know there are things like lodash, but wouldn't I have the same problem of a throttle running just as often on scroll? Any general approach help would be greatly appreciated. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(window).on('scroll', function() {
    var scrollPosition = $(window).scrollTop();
    if (scrollPosition &gt; 500) {
      $('.container').css('background-color', 'blue');
    } else {
      $('.container').css('background-color', 'red');
    }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    background-color: red;
    height: 2000px;
    width: 100%;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div class="container"&gt;
  
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>