timer

by ostapische

HTML

<div id="timerHolder"></div>
<button type="button" onclick="timer.stop;">Stop</button>
<button type="button" onclick="timer.reset;">Reset</button>

JavaScript

var Timer = function(holder){
    this.holder = holder;
    this.hoursHolder = document.createElement('font');
    this.hoursHolder.innerHTML = '00';
    this.holder.appendChild(this.hoursHolder);
    this.minutesHolder = document.createElement('font');
    this.minutesHolder.innerHTML = '00';
    this.holder.appendChild(this.minutesHolder);
    this.secondsHolder = document.createElement('font');
    this.secondsHolder.innerHTML = '00';
    this.holder.appendChild(this.secondsHolder);
    this.start = function() {
        this.interval = setInterval(this.tick, 1000);
    }
    this.stop = function() {
        if (this.interval) {
            clearInterval(this.interval);
        }
    }
    this.reset = function() {
        this.hoursHolder.innderHTML = '00';
        this.minutesHolder.innderHTML = '00';
        this.secondsHolder.innderHTML = '00';
    }
    this.tick = (function() {
        var seconds = parseInt(this.secondsHolder.innderHTML);
        var minutes = parseInt(this.minutesHolder.innderHTML);
        var hours = parseInt(this.hoursHolder.innderHTML);
        seconds++;
        if (seconds == 60) {
            seconds = 0;
            minutes++;
            if (minutes == 60) {
                minutes = 0;
                hours++;
                if (hours == 24) {
                    hours = 0;
                }
            }
        })(this);
        if (seconds < 10){seconds = '0' + seconds;}
        if (minutes < 10){minutes = '0' + minutes;}
        if (hours < 10){hours = '0' + hours;}
        this.hoursHolder.innderHTML = hours;
        this.minutesHolder.innderHTML = minutes;
        this.secondsHolder.innderHTML = seconds;
    }
}
var timerHolder = document.getElementById('timerHolder');
var timer = new Timer(timerHolder);
timer.start();