gpt4 book ai didi

javascript - 检查用户是否在 Firebase 中在线

转载 作者:行者123 更新时间:2023-11-30 20:57:04 25 4
gpt4 key购买 nike

我在 Google Firebase 文档中找到了我需要的示例 here .

不过,我还是想稍微修改一下,让它每秒/10 秒或至少每分钟检查一次用户是否存在,具体取决于这将如何影响服务器上的负载,所以我想出了这个:

TestApp.prototype.initFirebase = function() {
this.database = firebase.database();
this.database.ref(".info/connected").on("value", this.isOnline.bind(this));
};

TestApp.prototype.isOnline = function(snap) {
var i=0;
console.log(snap.val());
setInterval(function() {
if (snap.val() === true) {
console.log("connected"+(i+=10));
} else {
console.log("not connected");
}
}, 10000);
}

但如果我运行它,控制台会发生以下情况:

main.js:34 false
main.js:91 User signed out
main.js:34 true
main.js:39 not connected
main.js:37 connected10
main.js:39 not connected
main.js:37 connected20
main.js:39 not connected
main.js:37 connected30
main.js:39 not connected
main.js:37 connected40

它每 10 秒触发一次该函数,但它同时向我显示 connecteddisconnected 的结果。 (实际上,大约有 1 秒的延迟)此外,它完全忽略了用户是否登录,并且每次都向我显示相同的日志。

我希望它仅在用户登录(使用电子邮件和密码)时运行 isOnline 方法。如果这是真的,如果用户每 N 秒在线一次,isOnline 应该向服务器发送请求。有什么我可以做的吗?

如果我可以检查用户是否从服务器端连接会更好,因为只要用户保持在线,我就需要执行一些操作。但我不确定这是否可行,所以我认为最好的方法是使用 HTTP 触发器检查前端和触发器操作。

最佳答案

当前行为是由于 snap 的值造成的在定时器闭包中被捕获。

设置时 isOnlinevalue 上触发事件,每次键的值发生变化时,Firebase 都会调用该方法。在这种情况下,Firebase 调用了 isOnline第一次确定值为 false 时, 然后在建立登录后第二次,值变为 true .

现在里面isOnline ,您正在开始超时。由于使用不同的 snap 调用了两次函数。对象,创建了两个超时。但是他们两个都有自己的snap闭包中的对象,这些对象固定为 isOnline 时的值被调用。

作为最终结果,您有两个永久计时器在运行,它们不断打印历史记录 snap值(value)观 :).

正如您提到的,当且仅当用户在线时,您只想定期执行某些操作,您应该尝试这样做:

isOnline : function(snap){
let test = snap.val();
// If the user is not online,
// check if we had the timer set,
// as we should clear it now.
// It essentially means user went offline.
if (!test && this.whenOnline) {
clearTimeout(this.whenOnline);
this.whenOnline = null;
return;
}

// If the user is not online, return.
if (!test){
return;
}

// User is online. Install the timer if we haven't.
if (!this.whenOnline){
this.whenOnline = setTimeout(this.doSomethingWhenOnline, 10000);
}
}

doSomethingWhenOnline : function(){
// whatever;

// Cue the next timer again, notice we only install if
// the previous instance has not been cleared by the
// isOnline handler.
if (this.whenOnline){
this.whenOnline = setTimeout(this.doSomethingWhenOnline, 10000);
}
}

关于javascript - 检查用户是否在 Firebase 中在线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546716/

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