[英]Delay/Wait in between appending DIV in Ajax
I have below code where I am trying to display a message (in the form of DIV) by delaying certain amount of time in between appending div tags, I have only very little knowledge on Ajax, and tried to find a solution but I am not able to get it to work. 我在下面的代码中尝试通过在添加div标签之间延迟一定的时间来显示消息(以DIV格式),我对Ajax的了解很少,并试图找到解决方案,但我没有能够使其正常工作。
The below code when I try to execute it's not waiting for 2 seconds, and continuously appends div messages without any delay. 下面的代码在我尝试执行时不会等待2秒钟,而是连续不断地添加div消息而没有任何延迟。
Can someone guide me please? 有人可以指导我吗?
Here is my code 这是我的代码
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function wait_for_some_time() {
await sleep(2000);
}
$(function () {
$("#btn-chat").click(function (event) {
event.preventDefault();
if ($("#mes_resp").val() != "") {
$("#form-chat").submit();
}
});
$("#form-chat").submit(function (event) {
event.preventDefault();
var user_input = $("#mes_resp").val();
var pre_key = $("#pre_key").val();
if (user_input != "") {
$(".media-list").append('<div class="bubble-line"><div class="bubble bubble--alt">' + user_input + '</div></div> <div></div>');
if ((user_input == "yes" && pre_key == "duration")) {
i = 0;
while (i < 10) {
$(".media-list").append('<br>');
$(".media-list").append('<div class="thought"><div class="bubble">' + "Your request is in progress" + '</div></div> <div></div>');
$(".panel-body").stop().animate({ scrollTop: $(".panel-body")[0].scrollHeight }, 1000);
$("#mes_resp").val('');
wait_for_some_time();
i++;
}
}
}
$("#mes_resp").val('')
});
});</script>
尝试将await关键字放在对wait_for_some_time()函数的调用旁边。
I replaced with setInterval() and it worked great, In case if anyone is looking for 我将其替换为setInterval(),并且效果很好,以防万一有人在寻找
<script>
function continueExecution() {
$(".media-list").append('<br>');
$(".media-list").append('<div class="thought"><div class="bubble">' + "Your request is in progress" + '</div></div> <div></div>');
$(".panel-body").stop().animate({ scrollTop: $(".panel-body")[0].scrollHeight }, 1000);
$("#mes_resp").val('');
}
$(function () {
$("#btn-chat").click(function (event) {
event.preventDefault();
if ($("#mes_resp").val() != "") {
$("#form-chat").submit();
}
});
$("#form-chat").submit(function (event) {
event.preventDefault();
var user_input = $("#mes_resp").val();
var pre_key = $("#pre_key").val();
if (user_input != "") {
$(".media-list").append('<div class="bubble-line"><div class="bubble bubble--alt">' + user_input + '</div></div> <div></div>');
if ((user_input == "yes" && pre_key == "duration")) {
var timer;
timer = setInterval(function () {
i = 0;
while (i < 10) {
continueExecution();
i++;
}
clearInterval(timer);
}, 3000);
}
}
$("#mes_resp").val('')
});
});</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.