0

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.

  • 2
    No, you can't "pause" execution in JavaScript. Maybe instead of using `setInterval` you should use `setTimeout` and schedule the next update whenever the previous one is ready. – Felix Kling Oct 07 '20 at 10:15

1 Answers1

2

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
trincot
  • 317,000
  • 35
  • 244
  • 286