dongwen5870 2018-03-27 09:06
浏览 170
已采纳

PHP每隔5秒生成一个新的随机数

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();   
}


?>
  • 写回答

2条回答 默认 最新

  • dtest84004 2018-03-27 09:17
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示