倒数计时器,根据WebSocket接收的数据刷新

时间:2015-04-17 16:39:06

标签: javascript jquery timer countdown countdowntimer

我想用一个每秒刷新的WebSocket构建一个10秒的JQuery Countdown-Timer。它应该在x秒重置计时器(取决于我从WebSocket获得的数据)。如果我获得特定计时器的数据,它应该重新开始并再次从10秒开始倒数,但对于此特定计时器仅。 如果其中一个定时器降至0,则倒计时应完全停止。

目前我使用setInterval作为演示原因,但我想将这个定时器实现为WebSocket,如上所述:http://jsfiddle.net/alexiovay/azkdry0w/5/

JavaScript的:

var setup = function(){
  $('.count').each(eachSetup);    
};

var eachSetup = function(){
  var count = $(this);
  var sec = count.data('seconds') ;  
  count.data('count', sec);
};

var everySecond = function(){  
  $('.count').each(eachCount);    
};

var eachCount = function(){
  var count = $(this);
  var s = count.data('count');
  count.text(s);
  s--;
  if(s < 0) { 
    s = 0;
  }
  count.data('count', s);
};

setup();
setInterval(everySecond, 1000);

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>

我的WebSocket就像这样开始并每秒刷新一次:

var socket = io.connect('http://localhost:8000');   
socket.on('notification', function (data) {
    $.each(data.rows,function(index,row){   
...

1 个答案:

答案 0 :(得分:1)

如果您从套接字中获取 data.user data.seconds ,则可以执行以下操作:

var timers = []; // Creates an array to store your timers
socket.on('notification', function(data) { // Listen for 'notification' from socket
    if(timers.length > 0) {
        for(i in timers) {
            if(timers[i][0] === data.timer) {
                timers[i][1] = 10; // If timer for data.user already exists, set it to 10 seconds again.
            } else {
                timers.push([data.timer, data.seconds]); // Else, create it with data.seconds seconds
            }
        }
    } else {
        timers.push([data.timer, data.seconds]);
    }
}

function timerCount() {
    for(i in timers) {
        if(timers[i][1] <= 0) {
            delete timers[i]; // If timer seconds is less than 0, delete it.
        } else {
            timers[i][1]--; // Else, decrease it by 1 second.
        }
    }
}

setInterval(timerCount, 1000); // Runs the timerCount() function every second.