Skip to content
Advertisement

Progress Bar stopping when tab is not in focus

I’m using the following code for a progress bar:

<div class="slide-progress-bar">
  <div class="progress-bar" id="progress-bar"></div>
  <!--progress-bar-->
</div>
<script>
var elem = document.getElementById("progress-bar");
var width = 1;

function progressBar() {
  resetProgressBar();

  id = setInterval(frame, 300);

  function frame() {
    if (width >= 100) {
      clearInterval(id);
    } else {
      width++;
      elem.style.width = width +"%";
    }
  }
}
function resetProgressBar() {
  width = 1;
  elem.style.width = width;
}
progressBar()
</script>
<style>
.slide-progress-bar {
  width: 150px;
  background-color:rgba(155, 155, 155, 0.36);
  transition: width 10s linear;
  display: inline-block;
  vertical-align: middle;
  margin: auto;
  width: 100%;
}

.progress-bar {
  height: 5px;
  background-color: #ff4546;
  position: relative;
  transition: linear;
}
</style>

It works fine (when the page loads, progress bar starts and completes 300frames) but when I switch the tab or minimizes the window it stops and when I reopen the tab, it resumes. I don’t want this top happen. I want the progress bar to continue loading even when not in focus. Is there way to do so ?, cause I saw such progress bars on may other sites.

Advertisement

Answer

Set Interval stops when page is minimize. You can use Date object to check how many time pass since progress bar starts loading.

<div class="slide-progress-bar">
  <div class="progress-bar" id="progress-bar"></div>
  <!--progress-bar-->
</div>
<script>
var animationTimeInMiliseconds = 30000; //30s 
var interval = 300;
var elem = document.getElementById("progress-bar");
var beginningDate = new Date().getTime(); // Time in miliseconds

function progressBar() {
  resetProgressBar();

  id = setInterval(frame, interval);

  function frame() {
  var milisecondsFromBegin = new Date().getTime() - beginningDate;
  var width = Math.floor(milisecondsFromBegin / animationTimeInMiliseconds * 100);
  elem.style.width = width + "%";

    if (width >= 100) {
      clearInterval(id);
    }
  }
}
function resetProgressBar() {

  elem.style.width = 0;
}
progressBar()
</script>
<style>
.slide-progress-bar {
  width: 150px;
  background-color:rgba(155, 155, 155, 0.36);
  transition: width 10s linear;
  display: inline-block;
  vertical-align: middle;
  margin: auto;
  width: 100%;
}

.progress-bar {
  height: 5px;
  background-color: #ff4546;
  position: relative;
  transition: linear;
}
</style>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement