gpt4 book ai didi

javascript - 根据我通过 WebSocket 接收到的数据刷新的倒计时器

转载 作者:行者123 更新时间:2023-11-28 00:24:23 25 4
gpt4 key购买 nike

我想使用每秒刷新一次的 WebSocket 构建一个 10 秒的 JQuery 倒计时器。它应该在 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){
...

最佳答案

如果您从套接字获取data.userdata.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.

关于javascript - 根据我通过 WebSocket 接收到的数据刷新的倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com