Search code examples
javascriptfirebasefunctionasynchronouspause

How to pause a function for 2 seconds?


Hello i have the following code:

         function updateData(){
            
            return firebase.database().ref(varurl3).child('UserCount/count').once('value').then(function(snapshot) {
            var username = snapshot.val();
            var username2 = username+1; 
                
            return firebase.database().ref(varurl3).child('Users').child(username2).child('User').once('value').then(function(snapshot) {
            var username3 = snapshot.val();
            
            if(username3!= null){
                //Here i want to stop my function for 2 seconds
            }
            });
            
            });

        }

        timeupdater = setInterval(updateData, 100);

I want to pause my function when it goes into the if loop. I tried it with sleep, but the function always continued to run asyncron. Is there a way in my case to pause the function for 2 seconds so that it is not called again by timupdater at the bottom of the loop? I would appreciate helpful answers.


Solution

  • As Firebase already returns promises, use promises all the way. With async and await it simplifies to this:

    // Utility function to return a promise that resolves after a given delay
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    async function updateData(){
        let ref = firebase.database().ref(varurl3);
        let snapshot = await ref.child('UserCount/count').once('value');
        var username = snapshot.val();
        var username2 = username+1; 
        snapshot = await ref.child('Users').child(username2).child('User').once('value');
        var username3 = snapshot.val();    
        // resolve a promise after 2 seconds
        if (username3 != null) await delay(2000);
    }
    
    (async function looper() {
        while (true) { // forever
            await updateData();
            await delay(100); // this was the setInterval delay
        }
    })(); // execute looper