1

Hello everyone I am new to JavaScript and I want to have a countdown that automatically starts when the page loads, and only resume if the page is focused. Here is an example http://hp30405.pythonanywhere.com/mz7z5/.

How can I use this same logic in setTimeout(function() {}); ?

This is my script:

$(window).load(function() {
    var timeleft = 20;
    var downloadTimer = setInterval(function() {
        document.getElementById("timer").innerHTML = timeleft;
        timeleft -= 1;
        if (timeleft < 0) {
            clearInterval(downloadTimer);
            document.getElementById("timer").innerHTML = "20 sec done";
        }
    }, 1000);

    setTimeout(function() {
        $("#submit").removeAttr("disabled");
    }, 22000);
});
Blaztix
  • 1,223
  • 1
  • 19
  • 28
Techno Harsh
  • 81
  • 1
  • 10
  • https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Roko C. Buljan Feb 10 '19 at 12:02
  • sir you are not read my full question if page is load the countdown is start and if page is blur or focusout then countdown pause not end and if user back again on the pagr then countdown resume not restart – Techno Harsh Feb 10 '19 at 12:26
  • What stops you from implementing the suggested answers into your code? – Roko C. Buljan Feb 10 '19 at 12:41

1 Answers1

4

You use $(window).blur() and $(window).focus() to clearInterval and setInterval.Try this Unfotunately its not working in the snippet but works fine outside of snippet

let downloadTimer;
var timeleft = 20;
downloadTimer = setInterval(countDown, 1000);

function countDown() {
    document.getElementById("timer").innerHTML = timeleft;
    timeleft -= 1;
    if (timeleft < 0) {
        clearInterval(downloadTimer);
        document.getElementById("timer").innerHTML = "20 sec done";
    }
}

$(window).blur(function() {
    console.log("blurred");
    clearInterval(downloadTimer);
})
$(window).focus(function() {
    console.log("focuesed");
    downloadTimer = setInterval(countDown, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer"></div>
Blaztix
  • 1,223
  • 1
  • 19
  • 28
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73