我怎么能保持我的程序继续超过setTimeout

how can I keep my program from continuing past a setTimeout?

本文关键字:继续 setTimeout 程序 我的 怎么能      更新时间:2023-09-26

所以我有一个递归调用自己的计时器:

function introAnimation()
{
    var ostream = document.getElementById('table');
    var newhtml = '<h1>Ready?</h1><br/>';
    newhtml += '<h1>' + countdown-- + '</h1>';
    ostream.innerHTML = newhtml;
    if (countdown > 0)
        var a = setTimeout(function() {introAnimation()}, 1000);
}

,但问题是程序在完成计时器之前继续运行。是否有任何方法可以保持所有其他进程,直到指定的功能停止?

是否有办法保持所有其他进程,直到指定的功能停止?

是和不是。方法是无限循环(while(true) ;),但这是不希望的,因为它会冻结浏览器并且永远不会停止(因为超时不能拦截正在运行的函数)。所以你不应该。你真正想要请求的是:

如何在超时后延迟程序继续?

使用回调。你们已经在introAnimation中用过了,所以应该不难。将该函数更改为

function introAnimation(callback) {
    var ostream = document.getElementById('table');
    var newhtml = '<h1>Ready?</h1><br/>';
    newhtml += '<h1>' + countdown-- + '</h1>';
    ostream.innerHTML = newhtml;
    if (countdown > 0)
        var a = setTimeout(function() {introAnimation(callback)}, 1000);
    else
        callback();
}

和你的程序从

introAnimation();
// rest of program

introAnimation(function() {
    // part of the program that should run when the itro is done
});
// part of the programm that runs during the intro animation
// (might be nothing)