首页 > 解决方案 > Firebase 动态触发某些东西的正确方法

问题描述

让我首先用一个例子来描述你我想做什么:

- Players join a game (it's a web turn-based app/game with firebase/angular)
- When they are ready they have 30 seconds to choose a character
- Then player 1 has 30 sec to end his turn
- Then player 2 has 30 sec to end his turn
- ...

这是一个小回合制游戏,我很难结束一个回合。我考虑过在云函数上使用 cron 或 setInterval,但不建议使用 setInterval(成本高昂),而且 cron 也不是我想要的(我不想每天触发某些事情……)。我在两个相似的主题上看到了这些信息:

setInterval on firebase 而不是使用 cron && Cloud Functions for Firebase 按时触发?

正确的方法应该是什么(根据时间结束回合以增加游戏的“状态”)?

标签: firebasefirebase-realtime-databasetriggersgoogle-cloud-functions

解决方案


您可以在客户端 js 中使用 setInterval。在浏览器中运行 setInterval 是在 javascript 中预先确定的时间间隔后执行某些操作的正确方法。setInterval 不适用于云功能,但您不需要它们。

伪代码如下:

  1. 通过保存当前时间开始玩家的回合
  2. setInterval 开始时间 + 间隔
  3. 30 秒后,您的 setInterval 回调执行,您可以在其中更新游戏状态
  4. 冲洗并重复

推荐阅读