首页 > 解决方案 > 使用 setTimeout 链接承诺

问题描述

我有一个试图隐藏的“加载”动画,然后我需要淡入和淡出其他一些文本和按钮。下面的代码是我到目前为止所拥有的,但是then函数中的代码在hideLogoAnimation完成之前执行,这导致我的其余元素以错误的顺序显示和隐藏自己。

我在这里做错了什么?

这是一个显示问题的代码笔: https ://codepen.io/TheNomadicAspie/pen/OJmzpXy

function handleWelcome(is_first_time = true) {
    console.log('handleWelcome')
    traceFunction()
    hideLogoAnimation().then(() => {
        hideInputText()
        console.log('handleWelcome is_first_time is ', is_first_time)
        hideButton(left_button)
        console.log('handleWelcome user_dict is ', user_dict)
        setTimeout(() => {
            if (is_first_time) {
                showInfo("Some words")
                showButton(right_button, 'Next', handleFirstTime1)
            } else {
                showInfo("Welcome back")
                showButton(right_button, 'Start', handleTestStart)
            }
        }, 250)
    })
}

function hideLogoAnimation() {
    console.log('hideLogoAnimation')
    return new Promise(() => {
        setTimeout(() => {
            logo_animation.classList.remove('fadein')
            logo_animation.classList.add('fadeout')
        }, 500)
        setTimeout(() => {
            logo_animation.classList.remove('show')
            speech_bubble_middle_bar.style.display = 'unset'
            speech_bubble_bottom_bar.style.display = 'grid'
            freeze_input = false
        }, 750)
    })
}

标签: javascript

解决方案


在 Promise 中,您不会调用 resolve 或拒绝回调来触发 then() 或 catch(),因此在您的情况下,您必须在 setTimeout 中添加/删除淡入/淡出后调用 resolve。


推荐阅读