var oTimer; var Timer = function (pSeconds, pDisplay, pCallback, pAutoStart) { var me = this, tHandler = '', iTime = 0, sDisplay = '', fCallback = '', iTotSteps = 0, iCurrStep = 0; /* ***** Private Methods ******************************** */ function Step () { sDisplay.innerHTML = FormatTime(iTime) if (iCurrStep == iTotSteps) me.Stop(); else { iCurrStep++; iTime -= 1000; tHandler = setTimeout(Step, 1000); } } function FormatTime (time) { time /= 1000; var min = Math.floor((time %= 3600) / 60), sec = time % 60; return Pad(min) + ":" + Pad(sec); } function Pad (pNum) { return (! pNum ? '00' : (pNum < 10 ? '0' + pNum : pNum)); } function Init (pSeconds, pDisplay, pCallback, pAutoStart) { iTime = pSeconds * 1000; iTotSteps = pSeconds; iCurrStep = 0; sDisplay = document.getElementById(pDisplay); fCallback = pCallback; if (pAutoStart) me.Start(); } /* ****** Public Methods ******************************** */ // pSeconds; pDisplay: id of html element to display time left; pCallback: function to call when Stop this.Start = function () { Step(); } this.Stop = function () { if (tHandler) clearTimeout(tHandler); fCallback(); } // Init (pSeconds, pDisplay, pCallback, pAutoStart); } // Timer function doStart () { oTimer = new Timer(70, "theDisplay", doStop, 1); document.getElementById('message').innerHTML = ''; } function doStop (pFromButton) { if (oTimer && pFromButton) oTimer.Stop(); document.getElementById('message').innerHTML = 'TIMEOUT !!!!!!'; }
<p><button onclick="doStart()">Start</button> Time: <span id="theDisplay"></span></p> <p><button onclick="doStop(1)">Stop</button> <span id="message"></span></p>