Add tracking code on mouse move or on scroll

I’d like to load a tracking code only when a mouse is moved or a page is scrolled whichever comes first.

The code must be in pure js.

    let tracking_code_loaded = false;
    function addTrackingCode(){
        alert("Hi"); 
        // A code to add tracking code.
    }
    
    if (tracking_code_loaded == false) {
        document.onmousemove = addTrackingCode;
        tracking_code_loaded = true;
    }
    
    if (tracking_code_loaded == false) {
        document.onscroll = addTrackingCode;
    }

Now I imitate adding a tracking code by just saying “Hi”.

The problem with this code is that “Hi” constantly appears. That is the flag tracking_code_loaded doesn’t work.

Could you help me here?

Answer

I just want to catch the first event. And then ignore both the events.

Sound like you want to use EventTarget#addEventListener with once set to true.

const loadLogic = ((alreadyLoaded = false) => () => {
  if (alreadyLoaded) return;
  // TODO: Add loading logic
  console.log('loading logic');
  alreadyLoaded = true;
})();

document.addEventListener('mousemove', loadLogic, { once: true });

document.addEventListener('scroll', loadLogic, { once: true });
#filler {
  width: 1px;
  height: 700px;
}
<div id="filler"></div>