0

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?

10
  • 4
    You need setInterval(doRequest, 10000); (and remove the while loop). You were calling the function hundreds of thousands of times in the first second. Commented Jan 30, 2020 at 9:20
  • 2
    As for the 2nd part, first PHP finishes, then the result is sent back to the browser. Commented Jan 30, 2020 at 9:22
  • 3
    A setTimeout within a loop will not delay the loop. You just create an infinite number of setTimeouts that all fire 10 seconds later. Commented Jan 30, 2020 at 9:24
  • 2
    Also note that AJAX polling is an anti-pattern as it doesn't scale and causes server performance issues. If you need to keep the UI in sync with state changes on the server, use Websockets instead. Commented Jan 30, 2020 at 9:26
  • 1
    Here's an example of Ajax polling that might be worth a look - odds are you'd probably be better off with a websockets tutorial mind. Commented Jan 30, 2020 at 10:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.