I want to build a 10-seconds JQuery Countdown-Timer with a WebSocket that refreshes every second. It should reset the timer at x seconds (depending on the data I get from the WebSocket). If I get data for a specific timer, it should start over and counting down from 10s again, but only for this specific timer. If one of these timers drops to 0, the countdown should stop completely.
At the moment I use setInterval for demonstration reasons, but I want to implement this timers to the WebSocket as mentioned: 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>
My WebSocket starts like this and refreshes every second:
var socket = io.connect('http://localhost:8000');
socket.on('notification', function (data) {
$.each(data.rows,function(index,row){
...
If you're getting, say, data.user and data.seconds from the socket, you could do the following:
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.