user7994394
user7994394

Reputation:

Timer On Firebase Functions

I want To create a countdown timer on firebase cloud functions How can I make it ??

I am using firebase to make a mobile app using java . and I want to add a timer to my app that shows the same time to all users. but in this problem i want only to show a timer that counts time on the database

how can i make this timer with firebase cloud functions update i did this but there is an error in cmd

       const functions = require('firebase-functions');
      const admin=require('firebase-admin');

    admin.initializeApp(functions.config().firebase);   

      exports.myCloudTimer = 
     functions.database.ref('/startTimerRequest/').onCreate((event) => {
return db.ref('cloudTimer/timeInMs').once('value', snap => {
    if (!snap.exists()) {
        return Promise.reject('time is not defined in the database.');
    }

    let timeInSeconds = snap.val() / 1000;
    console.log('Cloud Timer was Started: ' + timeInSeconds);

    return functionTimer(timeInSeconds,
        elapsedTime => {
            db.ref('cloudTimer/observableTime').set(elapsedTime);
        })
        .then(totalTime => {
            console.log('Timer of ' + totalTime + ' has finished.');
        })
        .then(() => new Promise(resolve => setTimeout(resolve, 1000)))
        .then(() => event.data.ref.remove())
        .catch(error => console.error(error));
});
        });

       function functionTimer (seconds, call) {
        return new Promise((resolve, reject) => {
         if (seconds > 300) {
        reject('execution would take too long...');
        return;
           }
            let interval = setInterval(onInterval, 1000);
            let elapsedSeconds = 0;

        function onInterval () {
        if (elapsedSeconds >= seconds) {
            clearInterval(interval);
            call(0);
            resolve(elapsedSeconds);
            return;
        }
        call(seconds - elapsedSeconds);
        elapsedSeconds++;
    }
          });
                }

Upvotes: 4

Views: 7006

Answers (1)

Linxy
Linxy

Reputation: 2635

Okay, first go here: https://firebase.google.com/docs/functions/ and learn what a function is and how you can deploy your own.

Then deploy this 'myCloudTimer' function..

exports.myCloudTimer = functions.database.ref('/startTimerRequest/').onCreate((event) => {
    return db.ref('cloudTimer/timeInMs').once('value', snap => {
        if (!snap.exists()) {
            return Promise.reject('time is not defined in the database.');
        }

        let timeInSeconds = snap.val() / 1000;
        console.log('Cloud Timer was Started: ' + timeInSeconds);

        return functionTimer(timeInSeconds,
            elapsedTime => {
                db.ref('cloudTimer/observableTime').set(elapsedTime);
            })
            .then(totalTime => {
                console.log('Timer of ' + totalTime + ' has finished.');
            })
            .then(() => new Promise(resolve => setTimeout(resolve, 1000)))
            .then(() => event.data.ref.remove())
            .catch(error => console.error(error));
    });
});

function functionTimer (seconds, call) {
    return new Promise((resolve, reject) => {
        if (seconds > 300) {
            reject('execution would take too long...');
            return;
        }
        let interval = setInterval(onInterval, 1000);
        let elapsedSeconds = 0;

        function onInterval () {
            if (elapsedSeconds >= seconds) {
                clearInterval(interval);
                call(0);
                resolve(elapsedSeconds);
                return;
            }
            call(seconds - elapsedSeconds);
            elapsedSeconds++;
        }
    });
}

Then test it by creating a node called startTimerRequest:(put any value here)

enter image description here

Then you should see observableTime counting down from 7 to 1, 0 follows immediately after, and the request deletes itself.

So all your android users have to do, is observe the /cloudTimer/observableTime value, someone or something must trigger the countdown timer. You can trigger it manually, or have a user trigger it, or have a function trigger it, it depends on how and when you want to trigger it.

Caution: This code is not very safe, please add safeguards e.g. prevent multiple requests, or too long function execution (costs), etc... but it should work and get you started.

Upvotes: 6

Related Questions