gpt4 book ai didi

javascript - php脚本执行倒计时

转载 作者:行者123 更新时间:2023-11-30 10:17:13 24 4
gpt4 key购买 nike

我正在尝试在我的脚本中添加一个 COUNTDOWN,该脚本正在检查多个网站的一些因素,它会让用户实时知道在脚本完成任务之前还剩下多少小时/分钟/秒。我需要对我的 php 脚本执行此操作。但真的不知道从哪里开始。我只知道可以用 microtime() 函数来计算脚本执行的时间。我试着在这里搜索很多脚本,但我几乎没有找到与一些动态进度条相关的东西(但解释得不是很好),也没有找到可以倒计时脚本执行时间的动态倒计时计时器。非常感谢与此问题相关的任何帮助(链接、函数、脚本...)

最佳答案

如果不知道脚本的作用,就无法提前知道运行需要多长时间。即使我们确实知道它的作用,也无法真正知道运行所需的准确时间。如果这一切都在同一个 session 中,您可以在脚本的某些要点放置“% complete markers”。我在几个地方这样做。它是一个不错的进度条,我还显示了总运行时间。如果您想要这样的内容,请继续阅读...

(这是使用 jQuery UI progress bar ) enter image description here

如果您的脚本是一个循环,并且每次迭代基本上都在做同样的事情,那么进度条的增长将非常流畅。如果不是这种情况,并且你的脚本做很多事情非常快,然后一些事情非常慢,那么你的进度条就会像几乎所有的 Windows 进度条一样 :) 它可以很快到达某个点然后卡在那里一段时间。

不是在我的电脑上,所以我确定下面有拼写错误,但你应该能明白要点。希望这有助于...

像这样的东西会出现在你的长时间运行的脚本中......

$_SESSION["time_start"] = microtime(true);    
$_SESSION["percentComplete"] = 0;
... some of your php script ...
$_SESSION["percentComplete"] = 10;
... some of your php script ...
$_SESSION["percentComplete"] = 20;
... some of your php script ...
$_SESSION["percentComplete"] = 30;
... etc ...
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script

但是如果你的长时间运行的脚本是一个循环,它会更像这样......

$loopCnt = 0;
//your php loop
{
$loopCnt = $loopCnt+1;
//...the meat of your script...
$_SESSION["percentComplete"] = round(($loopCnt/$totalRecordCount)*100);
}
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script

然后在页面上,用户与 ajax ping 交互可以设置为每隔几秒左右检查一次 $_SESSION["percentComplete"] 的值,并使进度条根据结果。像...

function checkScriptProgress()
{
$.ajax({
url: "checkScriptProgress.php",
type: 'get',
cache: false,
success: function( data, textStatus, jqXHR) {
//(1) MOVE THE PROGRESS BAR
//if you are using a jQuery UI progress bar then you could do something like...
//jQuery("#yourProgressBar").progressbar( "option", "value", data.progress );
//if you are using HTML5 progress bars it would look like...
//var pBar = document.getElementById("yourProgressBar");
//pBar.value = data.progress;

//(2) UPDATE ELAPSED TIME
//if you want to display the total run time back to the user then use: data.totalRunTime

//(3) If report is not finished then ping to check status again
if (data.progress < 100) setTimeout("checkScriptProgress();", 1000); //check progress every 1 second so the progress bar movement is fluid
})
});
}

然后 checkScriptProgress.php 文件看起来像...

<?php
header('Content-Type: application/json');
$time_end = microtime(true);
$time = $time_end - $_SESSION["time_start"];
echo '{"progress":'.$_SESSION["percentComplete"].',"totalRunTime":'.$time.'}';
die();
?>

关于javascript - php脚本执行倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com