1

My setInterval timer is pausing when leave the tab and resume when switch back to the tab I want solution to make it keep counting when the tab is switched back

here is GIF picture shows what happen

enter image description here

here is my code:

  startCountDown(time) {
    clearInterval(this.countDownInterval);
    this.timeLeft = time * 100;
    if (time === 0) {
      return;
    }

    this.countDownInterval = setInterval(() => {
      this.timeLeft -= 1;
      if (this.timeLeft === 0) {
        clearInterval(this.countDownInterval);
      }
    }, 10);
  }
  updateTimer() {
    if (this.timeLeft > 0) {
      $('.rolling').fadeIn(200);
      $('.rolling-inner').html('<div>' + (this.timeLeft / 100).toFixed(2).replace('.', ':') + '</div>');
    } else {
      $('.rolling').fadeOut(200);
    }
  }
  set timeLeft(x) {
    this._timeLeft = x;
    this.updateTimer();
  }
  get timeLeft() {
    return this._timeLeft;
  }
Ameer Fakhri
  • 103
  • 1
  • 5

1 Answers1

2

Setinterval is not misbehaving , This is what it's property . But you can track the tab selection action and add the pending idle duration with existing time.

This is the code to track the tab selection and blur

$(window).on("blur focus", function(e) { 
    var prevType = $(this).data("prevType"); 

    if (prevType != e.type) { 
        switch (e.type) { 
            case "blur": break; 
            case "focus":  break; 
        } 
    } 

    $(this).data("prevType", e.type); 
})
Lansana Camara
  • 9,497
  • 11
  • 47
  • 87
Raja Mohamed
  • 1,026
  • 9
  • 22