1

Whenever I have a fast interval running to do a timer it will glitch out whenever a tab is switched as the interval is paused. Whenever I use a bigger interval it works pretty well but whenever I take a smaller one it will pause during the tab switch.

I would like a quicker timer that somehow doesn't pause, any ideas?

Code

var GLOBAL_TIMER_INTERVAL = 60 * 1000,
        GLOBAL_TIMER_TIMEOUT = 60 * 1000;

function countdownInterval(){
    var interval = setInterval(function(){
    if(GLOBAL_TIMER_INTERVAL <= 0){
        clearInterval(interval);
      return;
    }

    GLOBAL_TIMER_INTERVAL = GLOBAL_TIMER_INTERVAL - 10;
    $('.countdown-interval').text(GLOBAL_TIMER_INTERVAL);
  }, 10);
}

countdownInterval();

function countdownTimeout(){
    setTimeout(function(){
    if(GLOBAL_TIMER_TIMEOUT <= 0){
        return;
    }

    GLOBAL_TIMER_TIMEOUT = GLOBAL_TIMER_TIMEOUT - 10;
    $('.countdown-timeout').text(GLOBAL_TIMER_TIMEOUT);
    countdownTimeout();
    }, 10);
}

countdownTimeout();

JSFiddle

OrpheuZ
  • 37
  • 5

1 Answers1

0

A nonblocking timer:

  class Timer {
   constructor(task){
     this.task = task;
   }

   interval(ms){
     const end = +new Date() + ms;
     const check = () => {
       if(end > +new Date){
          this.task();
          interval(ms);
       } else {
          setTimeout(check, 100);
      }
      check();
    }
  }

So you can do:

  const log = new Timer(() => console.log("done"));
  log.interval(1000);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151