跨多个客户端同步的 Firebase 倒数计时器 [英] Firebase Countdown Timer Synched Across Multiple Clients

查看:26
本文介绍了跨多个客户端同步的 Firebase 倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将尝试使用 angular JS 为特定的利基市场构建一个便士拍卖网站.我正在尝试计划倒数计时器,并且我一直渴望尝试使用 firebase.

I am going to take a crack at building a penny auction site for a specific niche using angular JS. I am trying to plan the countdown timers and i've been itching for a reason to try out firebase.

昨天我有一个想法,让每个拍卖以某种方式在实际数据库中倒计时,因为通过 2 路数据绑定,人们的客户端将始终保持更新.

I had the idea yesterday to have each auction somehow have a countdown in the actual database, because with 2 way data binding, peoples clientside will always stay updated.

当 firebase 发生变化时,所有连接的客户端都会立即发生变化.所以我的问题是......我怎么能在特定记录中进行服务器端倒计时.

When the firebase changes, all the connected clients instantly change. So my question is this... How could I do a server side countdown within a particular record.

所以说我有一个项目 x 的记录,它有所有项目信息,数组键之一是倒计时:59:01:00".在 SERVER 端从 59:01:00 倒计时到 00:00:00 的现实且可扩展的方式是什么.

So say I had a record for item x and it had all that items information and one of the array keys is "countdown: 59:01:00". What is a realistic and scalable way to countdown from 59:01:00 to 00:00:00 on the SERVER side.

我在想也许是一个每 1 秒运行一次的 cronjob?但是如果有数百个数据库条目每秒运行数百个倒计时,服务器可能会崩溃.

I was thinking maybe a cronjob that runs every 1 second? But then with hundreds of database entries running hundreds of countdowns each second, the server would probably crash.

有什么好主意吗?

推荐答案

Firebase 确实可以每秒处理数百个数据库操作(实际上还有更多).但这会大大过度设计.

Firebase could indeed handle hundreds of database operations every second (many more in fact). But this would be greatly over-engineered.

不是在服务器上运行每秒更新一次的计时器,只需存储事件的开始/停止时间并允许客户端管理自己的计时器.这不应该通过每秒递减 1 来完成(因为 setInterval 和其他客户端工具不是很精确),而是通过将当前时间戳与结束进行比较并确定差异来完成.

Instead of running a timer that updates every second on the server, simply store the start/stop times of the event and allow the clients to manage their own timers. This should not be done by decrementing by 1 every second (as setInterval and other client-side tools are not very exact) but by comparing the current timestamp to the end, and determining the difference.

timeout = setInterval(countDown, 1000);
function countDown() {
    setTime(Math.max(0, endsAt - Date.now()));
    if( endsAt <= Date.now() ) { clearInterval(timeout); }
}

function setTime(remaining) {
    var minutes = Math.floor(remaining / 60000);
    var seconds = Math.round(remaining / 1000);
    $('#timer').text(lpad(minutes) + ':' + lpad(seconds));
}

很可能,您希望服务器负责计时器的原因是使其公平".但这不合逻辑.如果每个用户都保留自己的代码"到结束时间,并且开始/结束时间是固定的,那么这里就没有什么可破解的了.

Most likely, the reason you want the server in charge of the timer is to make it "fair." But this isn't logical. If each user keeps their own "ticker" down to the end time, and the start/end time are fixed, there is nothing to hack here.

这篇关于跨多个客户端同步的 Firebase 倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆