Ayan
Ayan

Reputation: 2918

setTimeout not giving the expected output

I have the following code but it doesn't seem to work properly. I cant understand why.

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";
}

Upvotes: 1

Views: 35

Answers (3)

Azeez Kallayi
Azeez Kallayi

Reputation: 2642

You can try setInterval() if you want to run this in every seconds.

 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>

Upvotes: 0

Vixed
Vixed

Reputation: 3509

As @Smiranin said, just call setTimeout outside of the function:

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

Or just use setInterval instead of SetTimeout

setInterval(updateBoard, 1000);

Upvotes: 0

vijayP
vijayP

Reputation: 11502

You can try with following approach:

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

Upvotes: 1

Related Questions