settimeout 没有被调用?

settimeout not getting called?

我有一个 javascript 调用服务器并获取 JSON 数据,其中包含一些配置 enable/disable 重定向到另一个 link。我需要将重定向延迟几秒钟,但似乎 setTimeout() 没有在我的方法中被调用。即使我将 redirect() 更改为匿名函数并将其传递给 setTimeout,它仍然没有被调用。

<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {   
    function redirect(){
        alert("in redirect");
        window.top.location=migrationConfig.REDIRECT_LINK;
    }       
    if (xhr.readyState == 4 && xhr.status==200) {
        var data = xhr.responseText;
        migrationConfig = JSON.parse(data);
        if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
            if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
                document.body.innerHTML = '';
                document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
                document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");                            
                setTimeout(redirect,3000);
            }

        }

    }
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

// 设置全局对象以便在 settimeout 函数中使用它

var redirect;

然后在 xhr.onreadystatechange = function() {

redirect = function(){
alert("in redirect");
        window.top.location=migrationConfig.REDIRECT_LINK;
}

setTimeout('redirect()',3000);

感谢所有建议。我根据 talsibony 的建议对其进行了改进,我还进一步发现 document.write() 删除了我的所有内容,这使得它无法找到重定向全局变量。所以我改为将其更改为添加 div 元素并设置 innerHTML。这是固定代码,以防有人遇到类似问题。

<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;

xhr.onreadystatechange = function() {       
    redirect = function(){
        window.top.location=migrationConfig.REDIRECT_LINK;
    }       


    if (xhr.readyState == 4 && xhr.status==200) {
        var data = xhr.responseText;
        migrationConfig = JSON.parse(data);
        if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
            if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
                document.body.innerHTML = '';
                var div = document.createElement("div");                    
                document.body.insertBefore(div, document.body.firstChild);
                div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
                div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
                div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
                setTimeout(redirect,3000);
            }

        }

    }
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);