简体   繁体   中英

Display a specific <div> content at setTimeout()

In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.

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>

The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.

Looking for a solution for this

Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:

// 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
    }
}

The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.

You're calling route2 recursively with setTimeout(route2,5000); under complete . So this will run infinitely as complete occur each time an ajax call is completed (wether success or error ). So what you can do is to create a timer and clear it after the second execution, something like this:

   var ctr = 0, timer =0;
   const route2 = function() {
    $.ajax({
        ...
        success: function (res) { 
         //Write you logic based on ctr
        }
        complete: function() {
            if(ctr>0){
              clearTimeout(timer)
            }else{
              timer = setTimeout(route2,5000);
              ctr = ctr+ 1;
            }

        },
     });
   };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM