//Declare a stopWatch "class"
function darkStopWatch(timerName) {
this.timerName = timerName;
this.timerSt = new Date();
this.resultQueue = [];
this.tag = "Test";
}
darkStopWatch.prototype = {
start: function(tag) {
this.tag = tag;
this.timerSt = new Date();
},
stop: function() {
var ts = new Date() - this.timerSt;
this.resultQueue.push(this.tag + " -> " + ts + "ms");
},
getRecord: function(clear) {
var s = this.resultQueue.join("\n");
if (clear) this.clear();
return "StopWatch [" + this.timerName +
"]\n====================\n" + s;
},
reset: function() {
this.resultQueue = [];
}
}
使用方法還蠻簡單的,利用new darkStopWatch("碼錶標籤")宣告物件,用start(“計時標籤")開始計時、stop()停止計時,darkStopWatch會將start()到stop()的時間記錄為該"計時標籤"的時間長度,並可反覆多次start()/stop(),最後則是用getRecord()取回所有計時結果。
以下的範例有三段,第一段是計算你按下alert確認鈕的時間長度、第二段是連續五次計時,每次長度為1秒,第三段則是示範一次可以使用多個碼錶。Check it out!
//Usage
var sw = new darkStopWatch("Alert Delay");
sw.start();
alert("請等待幾秒鐘再按下確定");
sw.stop();
alert(sw.getRecord());
//Use setTimeout go test the measure unit
function measure() {
var sw = new darkStopWatch("歸零射擊");
sw.start("Test 1");
var count = 1;
var hnd = setInterval(
function() {
sw.stop();
if (count < 5) {
count++;
sw.start("Test " + count);
}
else {
clearInterval(hnd);
alert(sw.getRecord());
}
},
1000);
//Demo 2, multiple stopwatches
window.swAry = [];
for (var i = 1; i <= 5; i++) {
swAry[i] = new darkStopWatch("Swatch " + i);
swAry[i].start("Wait for " + i + " sec");
setTimeout("swAry[" + i + "].stop()", i * 1000);
}
setTimeout(function() {
for (var i = 1; i <= 5; i++)
alert(swAry[i].getRecord());
}, 6000);
}
measure();