[显示特定的 setTimeout()的内容

问题描述 投票:0回答:1

在下面的代码中,我使用setTimeout()对我的后端node.js应用程序进行API调用,该API每5秒调用一次AJAX。在我的AJAX成功中,我根据某些条件显示divContent1divContent2,该条件应至少执行一次。之后,在每个divContent2调用中只有setTimeout()应该可见。

index.html

<script type="text/javascript">
$(document).ready(function(){         
    $.ajax({
             url: "http://localhost:8070/api/route1",
             type: 'POST',
             dataType:'json',                                         
             success: function(res) {
                 //Some Task               

            }
        });   
    $("#myButton").click(function(){
        const route2 = function() {
        $.ajax({
            url: "http://localhost:8070/api/route2",
            type: "POST",
            dataType: "json",
            data: { var1: val1 },
            success: function (res) { 

            // Various tasks
            if(res.flag){
                $("#divContent1").hide();
                $("#divContent2").show();
            }
            else{
                $("#divContent1").show();
            }

            //Functions that handle div content data

            },
            beforeSend: function() {
                $("#divContent1").hide(); 
                $("#divContent2").hide();
            },
            complete: function() {
                setTimeout(route2,5000);
            },
        });
    };
    $(function(){
        route2();
    })
    });
});                
</script>

setTimeout()调用整个route2函数,该函数处理div内容的所有显示和插入。但是,要求仅在第二个呼叫中显示divContent2

为此寻找解决方案

javascript jquery ajax settimeout setinterval
1个回答
0
投票

外部变量就足够了吗?只需在外部上下文中定义它,然后设置/检查它以选择行为即可:

// before declaring button click handler
var requestDoneAtLeastOnce = false;

// ...
// somewhere in success handler
success: function (res) {
    if (!requestDoneAtLeastOnce) {
        requestDoneAtLeastOnce = true;
        // do something that belongs only to handling the first response
    }
    else {
        // this is at least the second request, the other set of commands belongs here
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.