如何暂停功能 2 秒?

How to pause a function for 2 seconds?

您好,我有以下代码:

         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);

我想在函数进入 if 循环时暂停它。我在睡眠中尝试过,但该功能始终持续到 运行 asyncron。在我的例子中有没有办法暂停函数 2 秒,这样它就不会被循环底部的 timupdater 再次调用?我将不胜感激有用的答案。

正如 Firebase 已经 returns 承诺的那样,请始终使用承诺。使用 asyncawait 它简化为:

// 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