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.

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. 

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. 

```js
$(window).on('scroll', function() {
  var scrollPosition = $(window).scrollTop();
  if (scrollPosition > 500) {
    $('.container').css('background-color', 'blue');
  } else {
    $('.container').css('background-color', 'red');
  }
});
```

```css
.container {
  background-color: red;
  height: 2000px;
  width: 100%;
}
```

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">

</div>
```