/** Constructor with parameters * Make sure, the outputSpanID of two different instances * is not the same. Otherwise unpleasant things may happen. */ function Timer(count, interval) { this.count = count ? count : 0; this.interval = interval ? interval : 0; this.isPaused = false; this.intervalID = 0; this.outputSpanID = "time"; this.callback = null; } // init function Timer.prototype.init = function() { this.alert(); }; // alert the properties Timer.prototype.alert = function() { alert(this.count + ":" + this.interval + ":" + this.isPaused + ":" + this.intervalID); }; // print time Timer.prototype.printTime = function() { document.getElementById(this.outputSpanID).innerHTML = this.count; }; // start the timer Timer.prototype.start = function(e) { //clear interval if (this.intervalID != 0) { clearInterval(this.intervalID); } //print time this.printTime(); var self = this; //setInterval method sets the interval for repeating the function this.intervalID = setInterval(function() { self.count -= 1; if (self.count >= 0) { self.printTime(); } else { self.stop(); } }, self.interval); }; // stop timer Timer.prototype.stop = function() { //this.alert(); clearInterval(this.intervalID); this.count = 0; this.interval = 0; this.isPaused = false; this.printTime(); if(this.callback) { this.callback(); } }; // pause timer Timer.prototype.pause = function() { //this.alert(); clearInterval(this.intervalID); this.isPaused = true; }; // unpause timer Timer.prototype.unpause = function(e) { //this.alert(); this.start(); this.isPaused = false; }; /** * init method */ function init() { var timer2 = new Timer(100, 1000); timer2.outputSpanID = "time2"; //timer2.init(); timer2.start(); // get new instance of timer var timer = new Timer(); timer.outputSpanID = "time"; /* get the buttons and attach eventhandlers */ var startBtn = document.getElementById("startBtn"); var pauseBtn = document.getElementById("pauseBtn"); var stopBtn = document.getElementById("stopBtn"); startBtn.onclick = function() { timer.count = document.getElementById("timeBox").value; timer.interval = 1000; timer.start(); if (timer.isPaused === true) { pauseBtn.innerHTML = "pause"; } }; pauseBtn.onclick = function() { if (timer.isPaused === false) { timer.pause(); this.innerHTML = "unpause"; } else { timer.unpause(); this.innerHTML = "pause"; } }; stopBtn.onclick = function() { timer.stop(); }; } window.onload = init;
<form name="timeform"> <p> Time remaining: <span id="time">0</span> </p> <p> Time2 remaining: <span id="time2">0</span> </p> <p> <input type="text" id="timeBox" value=0 /> </p> <br/> <button type="button" id="startBtn">Start</button> <button type="button" id="pauseBtn">pause</button> <button type="button" id="stopBtn">Stop</button> </form>
#time{font-size:2em; font-weight:bold}