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スパイクを示します-通常の0.5%ではなく30〜40%。

これを行うより効率的な方法はありますか?

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常にグローバル スコープで実行されることに注意してください。

第 2 に、プログレス バーは通常、コストのかかるプロセスと一緒に作成されます。表示目的でのみ使用し、遅延を強制していますが、これは特に有用ではありませんが、レイアウトが気に入った場合は、それを使用できると思います.

通常の使用方法は次のとおりです。

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

あなたの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 に答える
1

関数 setInterval を試してください。

于 2012-12-12T21:35:39.427 に答える