0

I have few tabs, and on socket event I want to countdown for all opens tabs. I'm trying to do somethink like this:

var calendar = {
        timer: function (counter, id){
            var t = counter;
            var element = $(document).find('.view'+id);
            var parent = element.parent();
            var e = $('<div style="display: inline" id="timer'+id+'"></div>').appendTo(parent);
            var id = setInterval(function() {
                t--;
                if(t < 0) {                   
                    clearInterval(id);
                    e.remove();
                } else {
                    e.text(t);
                } 
            }, 1000);

        }
    }

but I have two problems: 1. This code I can execute for only one element. example:

div 1 -> and here is counting down. div 2 -> here isn't

And in div 1 on each tabs, countdown is different, but it starts at the same time. Coud someone help?

Jensej
  • 1,255
  • 6
  • 21
  • 33
  • 1
    could you provide a working pen or a fiddle please? – Tom M Jul 12 '17 at 15:57
  • http://jsfiddle.net/3QMzh/111/ hmm 2 divs working, but When I have opened 2 tabs, then countdown is different (start countdown is emit by socket.io – Jensej Jul 12 '17 at 16:04

1 Answers1

0

Considering your comment, as stated in this answer, inactive tabs have low priority execution and this can affect JavaScript timers.

Thus, a solution would be to listen to focus and then resync your socket.io timer.

window.addEventListener('focus', function () {
    // request socket.io response
})
Tom M
  • 2,815
  • 2
  • 20
  • 47