Search code examples
javascripttriggerssimplifydebouncingmouseleave

Simplify two functions with same functionalities?


I have two functions that do the same thing, but are used differently.

I currently have a popup that is triggered on actions based on device. On desktop, if the mouse leaves the page, it triggers the popup (function called exitUserMessage). On mobile, if the mouse is inactive for 10 seconds+ it triggers the popup (function called inactiveUserMessage). See below:

    //display popup for inactive users
        const inactiveUserMessage = () => {
        //other code was here but deleted bc not relevant
            return dismissModal();
        };
    
        //display popup for users leaving the page
        function exitUserMessage() {
        //other code was here but deleted bc not relevant
            return dismissModal();
        }

Here is where the functions are used, both separately for desktop and mobile:

    if (width <= 480) {
        // Start the timer on page load
        window.addEventListener("load", () => {
            timer = setTimeout(inactiveUserMessage, 10000);
        });
        document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000), timer);
    } else {
        // Trigger popup for desktop
        document.addEventListener("mouseleave", (e) => {
            if (Evergage.cashDom("#abandon-cart-message").length === 0) {
                return exitUserMessage();
            }
        });
    }

inactiveUserMessage is used in the debounce function that delays it by 10 seconds, then triggers the popup to show.

exitUserMessage is returned when the mouse leaves the page for desktop. My question is both of these functions are doing the same thing above ^.

Any ways to simplify? I am fairly new to JavaScript so looking to learn best practice!

Something worth noting: these are tracked as separate actions in our dataLayer.

Thank you!


Solution

  • You can call the inactiveUserMessage variable like functions. If there are different parts in those functions, add a parameter like isDesktop to inactiveUserMessage and debounce functions . If true, run the relevant desktop code in if statement.

    const inactiveUserMessage = (isDesktop) => {
      if (isDestop) {
        //Desktop
      } else {
        //Mobile
      }
    
      return dismissModal();
    };
    
    
    
    if (width <= 480) {
      // Start the timer on page load
      window.addEventListener("load", () => {
        timer = setTimeout(inactiveUserMessage, 10000);
      });
      document.addEventListener("mousemove", debounce(inactiveUserMessage, false, 10000), timer);
    } else {
      // Trigger popup for desktop
      document.addEventListener("mouseleave", (e) => {
        if (Evergage.cashDom("#abandon-cart-message").length === 0) {
          return inactiveUserMessage(true);
        }
      });
    }