Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1009 How can I have a stop watch that can be paused and unpaused?

You are here: irt.org | FAQ | JavaScript | Date | Q1009 [ previous next ]

Try:

<HTML>

<HEAD>

<SCRIPT LANGUAGE="JavaScript"><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }

var total = 0;

function start(no) {
    resetstartTime();
    timeoutID = setTimeout('keepWatching()', 1000);
    updateStatus();
}

function stop() {
    resetstartTime();
    clearTimeout(timeoutID);
    updateStatus();
}

function pause() {
    paused = !paused;
    if (paused) {
        clearTimeout(timeoutID);
        now = new Date();
        pauseTime = Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds());
        updateStatus();
    }
    else {
        now = new Date();
        resumeTime = Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds());
        pausedMilliseconds = pausedMilliseconds + resumeTime - pauseTime;
        timeoutID = setTimeout('keepWatching()', 1000);
        updateStatus();
    }
}

function keepWatching() {
    updateStatus();
    timeoutID = setTimeout('keepWatching()', 1000);
}

function resetstartTime() {
    now = new Date();
    startTime = Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds());
    pauseTime = 0;
    resumeTime = 0;
    milliseconds = 0;
    seconds = 0;
    pausedMilliseconds = 0;
}

function updateStatus() {
    if (!paused) {
        now = new Date();
        milliseconds = Date.UTC(y2k(now.getYear()),now.getMonth(),now.getDate(),now.getHours(),now.getMinutes(),now.getSeconds()) - startTime;
        seconds = (milliseconds - pausedMilliseconds) / 1000 - 1;
        if (seconds == -1)
            seconds = 0;
    }

    document.time.seconds.value = formatTime(seconds);
}

function formatTime(time) {
    var timeSeconds = time % 60;
    var timeMinutes = Math.floor(time / 60);
    return ((timeMinutes < 10) ? '0' + timeMinutes : timeMinutes) +
           ':' +
           ((timeSeconds < 10) ? '0' + timeSeconds : timeSeconds);
}

var timeoutID = 0;
var milliseconds = 0;
var seconds = 0;
var minutes = 0;
var startTime = 0;
var pauseTime = 0;
var resumeTime = 0;
var pausedMilliseconds = 0;
var paused = false;

var now = new Date();
//--></SCRIPT>

</HEAD>

<BODY>

<FORM NAME="time">
<INPUT TYPE="TEXT" NAME="seconds" SIZE="5">
<INPUT TYPE="BUTTON" VALUE="start" onClick="start()">
<INPUT TYPE="BUTTON" VALUE="Pause" onClick="pause()">
<INPUT TYPE="BUTTON" VALUE="Stop" onClick="stop()">

</FORM>

©2018 Martin Webb