My Website jitters when scrolling, whilst using the “onScroll” function to resize the header and Nav Bar

Hey everyone,

I am working on a small school project website, and I wanna make my header and nav bar change when scrolling past a certain point.

So far so good, I managed to do that. However there is a point where the website starts to freak out and switches very fast between the two states I set, as can be seen here:

Furthermore, the speed of the scroll slows down significantly upon reaching the point of change/where it freaks out, though I’d assume that simply is due to the function being called upon to many times.

As can be seen in the code, I tried adding some kind of cooldown on the function, this didnt really work (I did try it in a few more ways then the one currently in the code).

Ill be using the header as the code example, as Header and nav bar freak out in the same way.

HTML

<header id="header">
            <div>
                <h1 class="invisible">----</h1>
            </div>
</header>

CSS

header{
    background-color: #227C9D;
    position: sticky;
    top: 0;
    z-index: 2;
    height: 100px;
    transition: 0.2s;
}

JavaScript

var header;
var nav;
var delay = 800;
var lastChange = 0;

function scrollFunction() {
  header = document.getElementById("header");
  nav = document.getElementById("nav");
  

  if (document.body.scrollTop > 50 ) {
    if (lastChange >= (Date.now())) return;
    header.style.height = "50px";
    nav.style.fontSize = "20px";
    
  } else {
    if (lastChange >= (Date.now())) return;
    header.style.height = "100px";
    nav.style.fontSize = "40px";
    
  }
  lastChange = Date.now();



}

Full Code: https://github.com/DefenetlyNotSimon/InfoWebsiteProjekt/blob/beta/styles.css

If anyone has any ideas or solutions, I’d appreciate it 😀