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
2
Answers
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
You’re calling
route2
recursively withsetTimeout(route2,5000);
undercomplete
. So this will run infinitely ascomplete
occur each time an ajax call is completed (wethersuccess
orerror
). So what you can do is to create a timer and clear it after the second execution, something like this: