1

I used this code to count down when users were on my site. However it still works (countdown) when I work on another browser tab. Please help me

<style>
#permalink{display:none}
</style>
<script>
if (document.hasFocus())
  {
    var timeleft = 10;
var downloadTimer = setInterval(function(){
  if(timeleft <= 0){
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Done";
    document.getElementById("permalink").style.display = "block";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  }
  timeleft -= 1;
}, 1000);
  }
</script>
<div id="countdown"></div>
<div class="ebook-buttons">

<span id="download-button"><a id="permalink" href="/download/file.zip" rel="nofollow">Download</a></span>


</div>
Thanh Pham
  • 13
  • 2
  • So you need to figure out how to check if the tab is already being viewed? check this https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Zac Jan 24 '21 at 07:28

1 Answers1

0

You can use focus and blue event to identify that either user is on current tab or not. So check this solution:

<style>
    #permalink{display:none}
    </style>
    <script>
    var downloadTimer;
    var timeleft = 500;
    function startTimer() {
        downloadTimer = setInterval(function () {
            if (timeleft <= 0) {
                clearInterval(downloadTimer);
                document.getElementById("countdown").innerHTML = "Done";
                document.getElementById("permalink").style.display = "block";
            } else {
                document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
            }
            timeleft -= 1;
        }, 1000);
    }
    function stoptimer() {
        window.clearInterval(downloadTimer);
    }
    
    window.addEventListener('focus', startTimer);    
    window.addEventListener('blur', stoptimer);
    
    </script>
    <div id="countdown"></div>
    <div class="ebook-buttons">
    
    <span id="download-button"><a id="permalink" href="/download/file.zip" rel="nofollow">Download</a></span>
    
    
    </div>
Ankur Mishra
  • 1,284
  • 1
  • 6
  • 15