1

我的任务是制作一个进度条和一个进程持续时间计时器。所以,我没有三思而后行:

<div class="mainInfo">
    <div id="timer"><span id="elapsedText">0:00</span>/<span id="durationText">3:00</span></div>
    <div id="progressBar"><div id="progress" style="width:0;"></div></div>
</div>​

和 JS:

var time = 1000;
var duration = 180;

var $progress = $("#progress");
var $elapsedText = $("#elapsedText");

updateTime();

function updateTime() {
    var elapsed = time / 1000;
    $elapsedText.text(Math.floor(elapsed / 60) + ":" + Math.floor(elapsed % 60));
    $progress.css('width', (elapsed * 100 / duration) + "%");
    time = time + 1000;
    setTimeout("updateTime()", 1000);
}​

时间实际上是从另一个变量中检索的——这个用于演示(为了说明我实际上有以毫秒为单位的值)。

它有效(不仅在我的 PC 上),而且仍然有效,但是当这个周期运行时,procmon 在浏览器(chrome,ff)进程上显示 CPU 峰值 - 30-40% 而不是常规的 0.5%。

有没有更有效的方法来做到这一点?

4

5 回答 5

4

有一个标准函数:SetInterval(function, delay_in_ms)

它以毫秒为间隔调用一个函数。

于 2012-12-12T21:36:15.590 回答
3

代替

setTimeout("updateTime()", 1000);

采用

setTimeout(updateTime, 1000);

您每秒都在调用编译器这一事实确实会损害性能。将字符串传递给setTimeout基本上是evalsetTimeout.

于 2012-12-12T21:37:16.447 回答
2

有一个默认值,那就是setInterval.

请注意,作为第一个参数传递的函数setInterval始终在全局范围内执行。

第二,进度条通常与昂贵的流程一起创建。您仅将其用于显示目的并强制延迟,我认为这并不是特别有用,但如果您喜欢这种布局,我想您可以选择它。

您通常使用它的方式是:

executeFirstPotentiallyExpensiveProcess();// this is a call to a big function.
// then update the value of the progress bar in percentage style.
executeSecondPotentiallyExpensiveFunction()// this is the second part of your process.
// then again update..
// repeat until you have 100%.
// Basically, you logically divide the expenses of your various executions
// into numerable bits, preferably equal to one another for your convenience,
// but you chunk your loading process or whatever type of process and increment
// the progress after each chunk is complete.
于 2012-12-12T21:41:49.120 回答
1

尝试使用函数 setInterval。

于 2012-12-12T21:35:39.427 回答
1

你对 jQuery 的使用让我感到不安……

var time = 1000;
var duration = 180;

var $progress = document.getElementById("progress");
var $elapsedText = document.getElementById("elapsedText");

var beginTimestamp = new Date().getTime();

updateTime();
setInterval(updateTime,1000);

function updateTime() {
    var now = new Date().getTime();
    var elapsed = now-beginTimeStamp + time;
    $elapsedText.firstChild.nodeValue = Math.floor(elapsed / 60) + ":" + Math.floor(elapsed % 60);
    $progress.style.width = (elapsed * 100 / duration) + "%";
}​

也许没有 jQuery,您的浏览器可能会运行得更好;)

于 2012-12-12T21:39:46.357 回答