0
<div class="wait">Wait</div>
<div class="waitDownloadLink"></div>

$(document).ready(function()
                  {
                      var secondNormal = 40;
                      var refreshIntervalId;
                      refreshIntervalId = setInterval(function() {
                          secondNormal -= 1;
                          $(".wait").text(secondNormal);

                      }, 1000); 
                      setTimeout(function() {
                          clearInterval(refreshIntervalId);
                          $(".waitDownloadLink").text("Click me to download");
                      }, secondNormal * 1000);




                  });

When I start running the code and stay on the webpage, the code seems too work perfectly (or nearly). However, when I surf on other webpage right after I started the code, the timer is stuck between 12 - 18 second and then stops running. Why does this happen? And is there any solution to solve this?

https://jsfiddle.net/s1zf18co/

Joshua Leung
  • 2,219
  • 7
  • 29
  • 52

4 Answers4

1

Browsers typically pause or reduce thread priority for Javascript running in tabs that aren't visible. My guess is that it's a power saving measure for laptops and other things, but they all have done this for years now. This question has an incredibly thorough investigation into the issue.

The solution is to use web workers which don't get paused. See the Mozilla documentation for more information.

Community
  • 1
  • 1
Mordred
  • 3,734
  • 3
  • 36
  • 55
0

there is one working solution, try this and c if it is good enough, it is ok with leaving page problem, edit on end condition.

$(document).ready(function () {
    var secondNormal = 40;

    var refreshIntervalId = setInterval(function () {
        setTimeout(function () {
            if(secondNormal >0) {
                secondNormal -= 1;
            }
        }, 1000)

        $(".wait").text(secondNormal);
    }, 1000);
});
Vitaliy Terziev
  • 6,429
  • 3
  • 17
  • 25
0

Aside from Mordred's answer, in this case you may try using JS Date object to correctly estimate time. Check out this question.

Community
  • 1
  • 1
AlexanderM
  • 81
  • 1
  • 2
  • 7
0

I cannot seem to replicate the bug, however I believe that using the Date object may fix it:

var getDateTimeInSeconds = function() {
  return Math.floor(Date.now() / 1000)
};

$(document).ready(function() {
  var numOfSeconds = 40;
  var countFrom = getDateTimeInSeconds();
  var countTo = countFrom + numOfSeconds;

  var refreshIntervalId = setInterval(function() {
    var secondsLeft = countTo - getDateTimeInSeconds();
    if (secondsLeft < 0) {
      $(".wait").text(0);
      $(".waitDownloadLink").text("Click me to download");
      clearInterval(refreshIntervalId);
    } else {
      $(".wait").text(secondsLeft);
    }
  }, 1000);

});

Fiddle: https://jsfiddle.net/s1zf18co/1/

James G.
  • 2,852
  • 3
  • 28
  • 52