Search code examples
phprandomself-updating

Generate new random number every 5 seconds PHP


I need to update a variable number $x with a new random value every 5 seconds (length not really important). I know how to do it with a finite loop, however if I want it to be continuous and always just update. I know how to do it with just updating the header, but since I dont want the entire page to reload that is not really an option. Below Ive tried to trick it with a infinite loop (not the best way), but what I am also seeing running this is that it gives me the same number over and over.

Any ideas?

    <?php

echo "Random Number Updating <br>";
$n = 5;
$x = rand(1,10);

function random() {
    $interval = 5; // Interval in seconds
    srand(floor(time() / $interval)); 
    $x = rand(0, 10); 
    echo "$x";
}

while ($x <= 6){
 random();   
}


?>

Solution

  • In PHP(with refresh):

    while(true) {
        if( time() % 5 == 0 ) { // get time in seconds and check if it is multiple of 5
            echo rand(0, 10);
            break; // break the loop
        } else {
            sleep(1);
        }
    }
    header("Refresh:5"); // refresh after 5 seconds
    

    In JS(without refresh):

    <div id="update">--</div>
    <script>
        var update = document.getElementById("update");
        setInterval(() => update.innerHTML = Math.floor(Math.random() * 10), 5000);
        // 5 * 1000 ms = 5 seconds   ----------------------------------------^^^^
    </script>