'Change page title after specific time when user on other tab with other website

I am trying to change the title of my page after 1 minute, when visitor change the tab and changed tab should contain other website (for eg. www.youtube.com) and title should flashes alternatively after every 2 seconds with 'original title'and 'changed title'.

case 1: when 0 product added to cart, title of page should flashes with 'original title' and 'We miss you title'

case 2: When 1 or more products added into cart. title of page should flashes alternatively 'original title' and '1 product in your cart title'

case 3: When visitor come to original tab flashing of title should stop and it should show original title only.

var cartCount = parseInt($('.cart-count').text()); // gives cart count
var currentDomain = (document.domain); // current domain
var pageTitle = $(document).find("head title").text(); // page title

// checking tab change

document.addEventListener("visibilitychange", function() { 
  setTimeout(changeTitleFirst, 60000); // 1 minute timeout
  function changeTitleFirst(){
    setInterval(changeTitle, 2000);
    function changeTitle(){
      if(document.visibilityState === "hidden" && cartCount === 0){
          if(pageTitle !== "miss you"){
          $(document).find("head title").text("miss you");  
          } else {
          $(document).find("head title").text(pageTitle);
        }
      } 
      else if (document.visibilityState === "hidden" && cartCount > 0){
        if($(document).find("head title").text() !== "come back"){
           $(document).find("head title").text("come back");  
        } else {
          $(document).find("head title").text(pageTitle);
        }
      }
      else if (document.visibilityState !== "hidden"){
        $(document).find("head title").text(pageTitle);
      } else {
        return;
      }
    }   
  }
});



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source