[英]Display a specific <div> content at setTimeout()
在下面的代碼中,我正在使用setTimeout()
對我的后端 node.js 應用程序進行 API 調用,該應用程序每 5 秒調用一次我的 AJAX。 在我的 AJAX 成功中,我根據應至少執行一次的特定條件顯示divContent1
和divContent2
。 之后,在每個setTimeout()
調用中,只有divContent2
應該是可見的。
索引.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
。
尋找解決方案
外部變量就足夠了嗎? 只需在外部上下文中定義它並設置/檢查它以選擇行為:
// 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
}
}
setTimeout() 調用整個 route2 function 來處理 div 內容的所有顯示和插入。 但是,要求僅顯示第二次調用的 divContent2 。
您正在使用setTimeout(route2,5000);
route2
調用 route2; 下complete
。 因此,每次complete
ajax 調用( success
或error
)時,這將無限運行。 因此,您可以做的是創建一個計時器並在第二次執行后將其清除,如下所示:
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;
}
},
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.