php return result, wait, return result

71 views Asked by At

I'm trying to create a loop that isn't breaking my browser. This loop should get information from a SQL database every 10 seconds. So I tried this in JavaScript:

while(true) {
    setTimeout(doRequest(), 10000);
}

but it's just freezing the browser because it starts before the page is ready. I tried window.onload, document.onload and also $(document).ready() but nothing worked. There was always the error: document.onload is not a function.
Then I read about the Web Worker, but that didn't work either. So I decided to use PHP instead:
JavaScript:

function test () {
    $.post(
        "../../modules/communicator.php",
        {
            action: "test"
        },
        function(result) {
            console.log(window.location.href);
        }
    );
}

communicator.php:

if ($_POST['action'] == 'test') {
    echo("test");
    sleep(5);
    echo("hello");
}

but it returns testhello after 5 seconds.

Is there a way to return a string, wait 5 seconds, and then return the next one?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Thank you all! I fixed it! setInterval(doRequest, 10000);