当用户想要导出 CSV 数据时,我正在构建一个进度条。一切都按预期工作,直到我想在 while 循环中添加睡眠。
我尝试使用睡眠与刷新但没有成功。
为什么睡眠功能导致消息不输出?
sse.php
<?php
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
// perform queries
$lines = $res->rowCount();
$writtenLines = 0;
while ($row = $res->fetch(PDO::FETCH_NUM)) {
writeToCsv($row);
$writtenLines++;
sendMsg($writtenLines);
flush();
sleep(1);
}
function sendMsg($line) {
$data = [
"writtenLines" => $line,
"totalLines" => $lines
];
echo "data: ".json_encode($data)."\n\n";
}
客户
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
</div>
<br>
<span id="writtenLines">0</span> written lines
<script type="text/javascript">
var evtSource = new EventSource('sse.php');
evtSource.onmessage = (e) => {
const data = JSON.parse(e.data);
updateProgress(data);
if (data.writtenLines === data.totalLines)
evtSource.close();
}
function updateProgress(data) {
var p_bar = jQuery(".progress").find(".progress-bar");
document.getElementById("writtenLines").innerHTML = data.writtenLines;
status = parseInt(data.writtenLines/data.totalLines * 100);
p_bar.css("width", status + "%");
}
</script>
我也有同样的问题,我需要睡眠以避免服务器超载