首页 > 解决方案 > 在继续之前等待最短时间

问题描述

我有这个函数等待 is_user_dict 返回 true,然后将一些配置文件数据上传到数据库并继续执行程序。在发生这种情况时,如果功能的其余部分花费的时间少于完成的时间,我想播放至少 2 秒的动画。

以前我使用 setTimeout 处理这个问题,但这会阻止函数在等待期间实际执行任何操作,从而不必要地减慢程序速度。确保 showLogoAnimation 运行至少 2 秒但不超过所需时间的最佳方法是什么?

我知道我可以测量 start_time 和函数准备好的时间之间的时间,并使用一个 while 循环,直到过了这么多时间,但我知道我的代码已经很草率,并且可能有更好的方法来做我的事情我在做什么?

async function handleTestStart() {
    traceFunction()
    character.style.backgroundImage = "url(character.png)"
    left_button.style.visibility = 'visible'
    right_button.style.visibility = 'visible'
    showLogoAnimation()
    let start_time = new Date().getTime()
    while (!is_user_dict) {
        let end_time = new Date().getTime()
        let time = end_time - start_time
        if (time > 10000) {
            timeoutError()
        }
    }
    let is_profile_ready = createProfile()
    let start_time2 = new Date().getTime()
    is_profile_ready.then((result) => {
        let end_time2 = new Date().getTime()
        let time2 = end_time2 - start_time2
        if (time2 > 10000) {
            timeoutError()
        }
        hideLogoAnimation()
        condition_category_array.forEach(function (condition_category) {
            user_dict['more_info'].push(condition_category)
        })
        category = user_dict['more_info'][0]
        backup_user_dict = deepCopyObject(user_dict)
        nextQuestion()
    })
}

标签: javascript

解决方案


推荐阅读