首页 > 解决方案 > PHP While 循环没有中断,但可以在调试器中使用?

问题描述

有一个循环的简单脚本。当我单步执行代码时,在调试器模式下工作正常。但是,当它在没有调试器的情况下运行时,它永远不会结束/中断。

只要我设定的时间就应该运行,然后跳出循环。正如我所说,这在调试器中工作得非常好,但是当它没有它运行时,它只是永远循环,不管时间

任何建议为什么?

$time_start = microtime(true);
$n = 0;
while ( 1 ){
    $n++ ;
    echo $n;
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    if($time > 1.5){
        break;
    }
}

我想使用 While,因为程序将用于侦听套接字。但如果满足时间,需要确保时间结束

标签: phpwhile-loop

解决方案


它可以工作,但 PHP 非常快。所以你必须更加耐心,直到时间过去。降低门槛。

也许您应该考虑改用hrtime

当您使用调试器时,时间仍在运行,因此到达下一步之前的延迟很快结束并满足中断条件。

$time_start = microtime(true);
$n = 0;
while ( 1 ){
    $n++ ;
    echo $n;
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo " :: $time\n";
    if($time > 1.5){
        break;
    }
}

在稍微修改输出后查看最后的结果。

1354524 :: 1.4999921321869
1354525 :: 1.4999930858612
1354526 :: 1.4999940395355
1354527 :: 1.4999949932098
1354528 :: 1.4999949932098
1354529 :: 1.4999961853027
1354530 :: 1.4999971389771
1354531 :: 1.4999980926514
1354532 :: 1.4999990463257
1354533 :: 1.4999990463257
1354534 :: 1.5
1354535 :: 1.5000011920929

推荐阅读