gpt4 book ai didi

javascript - setTimeout 的计时问题

转载 作者:搜寻专家 更新时间:2023-11-01 04:54:00 24 4
gpt4 key购买 nike

下面的代码演示了我遇到的问题。

当 js 执行时,进度条会像预期的那样快速填充,直到达到最大值。

但是,span#pbarval 容器更新非常缓慢,并且在进度条完成后 LONG 完成。

$(document).ready(function () {
var max= 20000,
cur=0;
function updatePBar(){
cur++;
jQuery("#pbar").val(cur);
jQuery("#pbarval").html("" + Math.ceil(cur*100/max) + "%");
if (cur<=max){
setTimeout(updatePBar, 10);
}
}
updatePBar();
});

您可以在此处看到执行的代码:http://jsfiddle.net/EricBrian/fhtp6rpf/

谁能解释一下这是为什么?如何让它跟上进度条?

此外,我注意到如果我切换选项卡,setTimeout 似乎会暂停。在我切换回运行它的选项卡之前,百分比不会更新。

谢谢!-e

最佳答案

您正在使用 cur为进度条的值,所以当cur === 100时进度条满了,但您显示的是 cur*100/max作为未达到 100% 的百分比直到 cur == 20000 .

您应该使用相同的公式 cur*100/max对于两者,并且由于您想要快速的速度,您还应该将最大值除以 100:

http://jsfiddle.net/Paulpro/fhtp6rpf/2/

$(document).ready(function () {
var max= 200,
cur=0;
function updatePBar(){
cur++;
jQuery("#pbar").val(cur*100/max);
jQuery("#pbarval").html("" + Math.ceil(cur*100/max) + "%");
if (cur<max){
setTimeout(updatePBar, 10);
}
}
updatePBar();
});

我也改了测试cur<=maxcur<max因为你可能不想增加 cur已经在 max 的额外时间.

关于javascript - setTimeout 的计时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31215177/

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