javascript

时间:2017-02-16 00:45:52

标签: stopwatch

我的目标是使用秒表功能进行6次不同的时间试验。我在javascript(https://gist.github.com/electricg/4372563)中使用了electricg的秒表。这对我来说输出第一个结果(试验一次)很好,但我的挑战是输出第二个结果(试验二)独立于第一个结果。

var	clsStopwatch = function() {
    // Private vars
    var	startAt	= 0;	// Time of last start / resume. (0 if not running)
    var	lapTime	= 0;	// Time on the clock when last stopped in milliseconds

    var	now	= function() {
        return (new Date()).getTime();
    };

    // Public methods
    // Start or resume
    this.start = function() {
        startAt	= startAt ? startAt : now();
    };

    // Stop or pause
    this.stop = function() {
        // If running, update elapsed time otherwise keep it
        lapTime	= startAt ? lapTime + now() - startAt : lapTime;
        startAt	= 0; // Paused
    };

    // Reset
    this.reset = function() {
        lapTime = startAt = 0;
    };

    // Duration
    this.time = function() {
        return lapTime + (startAt ? now() - startAt : 0);
    };
};

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
    var s = "0000" + num;
    return s.substr(s.length - size);
}

function saveTrialOne() {
    var trial_time = $time.innerHTML;
    $('.trial-one').append('Trial 1 Result ' + trial_time + ' seconds');
}

function saveTrialTwo() {
    var trial_time = $time.innerHTML;
    $('.trial-two').append('Trial 2 Result ' + trial_time + ' seconds');
}

function formatTime(time) {
    var m = s = ms = 0;
    var newTime = '';

    m = Math.floor( time / (60 * 1000) );
    time = time % (60 * 1000);
    s = Math.floor( time / 1000 );
    ms = time % 1000;

    newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
    return newTime;
}

function show() {
    $time = document.getElementById('time');
    update();
}

function update() {
    $time.innerHTML = formatTime(x.time());
}

function start() {
    clocktimer = setInterval("update()", 1);
    x.start();
}

function stop() {
    x.stop();
    clearInterval(clocktimer);
}

function reset() {
    stop();
    x.reset();
    update();
}
<body onload="show();">
  <div>Time: <span id="time"></span></div>
   <input type="button" value="start" onclick="start();">
   <input type="button" value="stop" onclick="stop();">
   <input type="button" value="reset" onclick="reset()">
   <button type="button" onclick="saveTrialOne()">Save</button>
  <!-- output trial one -->
<h6><span class="trial-one"></span></h6>

<div>Time: <span id="time"></span></div>
  <input type="button" value="start" onclick="start();">
  <input type="button" value="stop" onclick="stop();">
  <input type="button" value="reset" onclick="reset()">
  <!-- output trial two -->
  <button type="button" class="btn" onclick="saveTrialTwo()">Save</button>
        
<h6><span class="trial-two"></span></h6>

</body>

0 个答案:

没有答案