javascript - 通过调用python脚本为Javascript函数调用添加延迟
问题描述
我已经研究了很多使用setInterval
and的解决方案setTimeout
,但是我认为我可以尝试使用 python 脚本在函数调用之间添加延迟。
解释代码:
我有一个下拉菜单,其中包含今天正在播放的足球比赛。当用户从这个下拉列表中选择一个选项时,即它检测到一个
change
,然后它会执行一堆代码来使用相关信息更新页面。在这个函数中,我还有另一个函数
liveCommentaryCall()
,它使用 AJAX 来获取从下拉菜单中选择的足球比赛的最新更新。- 当然,我需要每隔 X 秒调用一次以更新有关最新事件的网页。
- 在函数结束时,我
POST
向特定 URL 发出 AJAX 请求/delayRequest
,然后我在烧瓶中让该路由简单地执行 asleep()
并返回。 - 在此之后,我再次调用该函数
liveCommentaryCall()
以重新启动更新过程。
JAVASCRIPT
$("#teamDropdownSelector").change(function(){
.
.
.
function liveCommentaryCall(){
alert("called");
.
. // bunch of code to update the page
.
$.ajax({
url: "/delayRequest",
type: "POST",
data: JSON.stringify(""),
success: function(response) {
alert("RESPONSE RECIEVED");
},
error: function(delayError) {
alert("Something's gone wrong!");
}
});
liveCommentaryCall();
}
//Now out of the function scope.
//Below is the first time the liveCommentaryCall function gets called.
liveCommentaryCall();
});
PYTHON
@app.route("/delayRequest", methods=['POST', 'GET'])
def delay():
time.sleep(10)
return;
然而,与调用该函数相反,它运行,然后在再次调用之前有 10 秒的延迟,该网页只是用“调用”警报来提醒我,这意味着liveCommentaryCall
只是在某处循环时立即被调用?
我在代码中看不到任何应该导致这种情况的地方,这让我认为我忽略了一些基本原则。
问题
是我不能使用这样的python脚本,还是我没有正确编码这个想法?
解决方案
liveCommentaryCall
您可以使用以下setInterval
函数,而不是递归实现script
:
<script>
setInterval("liveCommentaryCall()",1000); //call every second
function liveCommentaryCall(){
.
. // bunch of code to update the page
.
$.ajax({
url: "/delayRequest",
type: "POST",
data: JSON.stringify(""),
success: function(response) {
alert("RESPONSE RECIEVED");
},
error: function(delayError) {
alert("Something's gone wrong!");
}
});
}
</script>
推荐阅读
- azure - 如何在带有会话 ID 的 Azure 服务总线队列中发送和接收消息?
- python - Pyqt5 - QComboBox 在填充元素时非常慢
- python - 导出数据到excel,只得到最后一行
- python - 随着时间的推移验证连续条件
- javascript - 从 JSON 文件接收 JavaScript 对象后正确访问它
- c# - 画线不出现
- scala - spark scala 类型与 groupbykey 中的 zipwithIndex 不匹配
- fft - 对音频样本运行 FFT 后如何确定截止幅度?
- c++ - 如何正确地将 shared_pointer 传递给构造函数?
- responsive-design - 如何将文本旁边的图像与显示对齐:flex(响应式)