Brandon Wong
Brandon Wong

Reputation: 49

How do I prevent PHP sleep function from stopping my HTML page

I am currently trying to write a dice game. When the user clicks "Play" the dice will start changing. One die is the user's and one is the server's. While this is happening, my PHP page will wait 5 seconds and then calculate a random number. It will then send it to the HTML page and once the HTML receives it, it'll stop the dice and declare a winner. I am currently stuck on the PHP part and tried using the sleep function. However, when I do this if I click Play the dice won't move until it has received the number and then it'll start to shuffle. This is my code so far.

HTML/JS

<body>
    <h1>Brandon Wong</h1>
    <input type="button" id="play" value="Play">
    <div id = "userDie"></div>
    <div id = "serverDie"></div>
    <script>
        document.querySelector('input[type]').addEventListener('click', toss_dice);

        //display default dice*/
        var userDie = document.createElement('img');
        var serverDie = document.createElement('img')
        userDie.src = '1.gif';
        serverDie.src = '1.gif';
        document.getElementById('userDie').appendChild(userDie);
        document.getElementById('serverDie').appendChild(serverDie);

        function toss_dice() {
            var dice = ['1.gif', '2.gif', '3.gif', '4.gif', '5.gif', '6.gif'];
            var randPlayer2 = 0;
            setInterval(function(){
                var randPlayer1 = Math.floor(Math.random() * dice.length);
                var randPlayer2 = Math.floor(Math.random() * dice.length);
                userDie.src = dice[randPlayer1];
                serverDie.src = dice[randPlayer2];
                document.getElementById('userDie').appendChild(userDie);
                document.getElementById('serverDie').appendChild(serverDie);
                //alert(randPlayer1);
            }, 500);

            request = new XMLHttpRequest();
            request.open('GET', 'hw02.php', false);
            request.send(null);

            var test = request.responseText;
            alert(test);
        }

    </script>

PHP

<?php 
    sleep(5); 
    $number = rand(0,5); 
    echo $number:
?>

Here's a link to my page to see my page so far

Upvotes: 3

Views: 162

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

Your request is currently using , false for a blocking request. This will prevent animations and other JS and such from running on the page while the request is in progress. Synchronous requests are deprecated and can result in a bad user experience (as you're seeing) - use a proper async request instead.

request.addEventListener('readystatechange', () => {
  if (request.readyState === 4) {
    console.log(request.responseText);
  }
});
request.open('GET', 'hw02.php');

Upvotes: 2

Related Questions