首页 > 解决方案 > 通过调用python脚本为Javascript函数调用添加延迟

问题描述

我已经研究了很多使用setIntervaland的解决方案setTimeout,但是我认为我可以尝试使用 python 脚本在函数调用之间添加延迟。

解释代码:

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脚本,还是我没有正确编码这个想法?

标签: javascriptjqueryajax

解决方案


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>

推荐阅读