Javascript 除非使用sleep(),否则PHP进度跟踪无法在foreach循环中正常工作

Javascript 除非使用sleep(),否则PHP进度跟踪无法在foreach循环中正常工作,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有一个用于跟踪php执行进度的小php函数。进度被放入一个txt文件中,大约每0.1秒用js函数检索一次 现在的问题是,只有使用sleep(1)时,进度条才会更新

我有一个用于跟踪php执行进度的小php函数。进度被放入一个txt文件中,大约每0.1秒用js函数检索一次

现在的问题是,只有使用
sleep(1)时,进度条才会更新refreshProgress()
函数运行了大约40次,这足以在大约12个循环中保存txt文件中的数据

另外,通过在保存后回显文件内容,我可以看到正确保存了百分比,因此我不确定问题出在哪里,我明确不想使用sleep函数,因为稍后我将在大量数据上运行脚本

这里有两张图片展示了使用睡眠(1)和不使用睡眠(1)时的区别 以下是PHP脚本:

$cars = array
      (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );

$cars_all_count = 13;
$file = "to/this/path/progress.txt";
$i = 0; 

foreach ($cars as $key=>$carslist){
// some function
    foreach($carslist as $single_car){

    $start = microtime(true);
    $i++;

    // usleep(250000);

    UpdateProgress( $file, $i, $cars_all_count );

    $time_elapsed_secs = microtime(true) - $start;
    echo '<pre>loop:'.$i.'<br>';
    print_r($time_elapsed_secs);
    echo '<pre>';

    }
}

function UpdateProgress( $file, $i, $cars_all_count ) {
    // Calculate the percentatage.
    $percent = intval($i/$cars_all_count * 100);
    // Put the progress percentage and message to array.
    $arr_content = $percent;
    // Write the progress into a file
    file_put_contents($file, $arr_content);
    echo file_get_contents($file).'<br>';
}

console.log(响应)中的区别是什么
当您使用和不使用
睡眠时
?“大约每0.1秒用js函数检索一次”。您是说每100毫秒执行一次get请求吗?考虑到您的请求在该时间段内没有完成的可能性很大,这太过分了。@Goose不带
sleep()
它只返回空值,带
sleep()
它返回正确的百分比听起来好像有错误,并且您已经完成了错误报告。启用错误报告并检查错误。这些错误消息将使这一点更容易理解。@Taplar确切地说,我将增加它,只是试图找出发生这种情况的原因,基本上消除了get函数被延迟的可能性。
console.log(response)中的区别是什么
当您使用和不使用
睡眠时
?“大约每0.1秒用js函数检索一次”。您是说每100毫秒执行一次get请求吗?考虑到您的请求在该时间段内没有完成的可能性很大,这太过分了。@Goose不带
sleep()
它只返回空值,带
sleep()
它返回正确的百分比听起来好像有错误,并且您已经完成了错误报告。启用错误报告并检查错误。这些错误消息将使这一点更容易理解。@Taplar确切地说,我将增加它,只是试图找出发生这种情况的原因,基本上消除了get函数被延迟的可能性。
function refreshProgress() {
    var progress_url = progress_file_link;

    jQuery.get(progress_url, function(response) {
         console.log(response);
        if (response.length == 0){
            return false;
        }
        var parsedData = response;
        jQuery("#progress").find('.bar').css('width', parsedData + '%');

        // console.log(parsedData);
        // If the process is completed, we should stop the checking process.
        if (parsedData == 100) {
            window.clearInterval(timer);
            completed();
        }
    });
}