setTimeout没有给出预期的输出

时间:2017-01-22 10:23:16

标签: javascript php jquery settimeout

我有以下代码,但它似乎无法正常工作。我不明白为什么。

JS

var updateBoard = function() {
        $.ajax({
            type: "POST",
            url: "engine/main.php",
            data: {codes: 2},
            success: function(response) {
                console.log(response);
            }
        });
        setTimeout(updateBoard, 1000);
    };

PHP

if(isset($_POST['codes'])) {
    echo "test";
}

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

var updateBoard = function() {
        $.ajax({
            type: "POST",
            url: "engine/main.php",
            data: {codes: 2},
            success: function(response) {
                console.log(response);
                setTimeout(updateBoard, 1000); //calling the function after 1 sec after we get the response
            }
        });

    };

updateBoard(); //calling it right away

答案 1 :(得分:0)

正如@Smiranin所说,只需在函数外部调用 setTimeout

var updateBoard = function(){
    $.ajax({
        type: "POST",
        url: "engine/main.php",
        data: {codes: 2},
        success: function(response) {
           console.log(response)
        }
    })
};
setTimeout(updateBoard, 1000);

或者只使用 setInterval 而不是SetTimeout

setInterval(updateBoard, 1000);

答案 2 :(得分:0)

如果要在每秒钟内运行此命令,可以尝试使用setInterval()。



 var updateBoard = function() {
        $.ajax({
            type: "POST",
            url: "engine/main.php",
            data: {codes: 2},
            success: function(response) {
                console.log(response);
            }
        });
        
    };
	setInterval(updateBoard, 1000);
	

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;