DThink DThink - 2 months ago 21
Javascript Question

firebase, listen only last childrens by date

in my app i use this code to listen only the childrens added after the current time

var start = new Date().getTime();

firebase.database().ref(path).orderByChild('created').startAt(start).on('child_added', function(value){
console.log(value.val());
});


in the browser this method work well. i see the child only if i start to add it after the current time.
in the smartphone this method not work, it work only if i start to add a children after a certain amount of seconds. i think that this happen because the current time of the smartphone is different by the current time of the server. is there any way to fix this without having to take the last element ??

Answer

If the clock on your phone is off, this will not work reliably.

Firebase detects the offset of the local clock to the server time and exposes this in a value .info/serverTimeOffset. You can use this to correct for the clock skew as explained in the documentation on clock skew:

var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
  var offset = snap.val();
  var estimatedServerTimeMs = new Date().getTime() + offset;
});

Read the linked documentation for a full explanation.