I'm using the countdown timer from here: The simplest possible JavaScript countdown timer?
I'm adding the reset, pause and resume functionalities to the code.
//=================== Timer class ==============================
function CountDownTimer(duration, granularity) {
this.duration = duration
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
this.resetFlag = false;
}
CountDownTimer.prototype.start = function() {
console.log('calling start');
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj,
timeoutID;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (that.resetFlag) {
console.log('Reset inside closure');
clearTimeout(timeoutID);
diff = 0;
that.resetFlag = false;
that.running = false;
return;
}
console.log(diff);
if (diff > 0) {
timeoutID = setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.prototype.setTime = function(secs) {
this.duration = secs;
}
CountDownTimer.prototype.reset = function() {
this.resetFlag = true;
}
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
window.onload = function () {
timer = new CountDownTimer(25);
timer.start();
$('#button').click(function() {
console.log("before reset");
console.log(timer);
console.log("after reset");
timer.reset();
console.log(timer);
// timer.setTime(10);
timer.start();
})
}
HTML for testing, check the output at console.
<script src="main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button id='button'> </button>
1) Is function timer() in start a closure?
2) I added a resetFlag, the reset method, and the check for resetFlag in the start function. I'm able to stop the timer immediately, but can't start it after that. How do I fix the error?
25
24
23
main.js:64 Reset inside closure
(it supposed to countdown from 25 to 0, and when I press #button, the timer reset and should count from 10 to 0.
================================EDITS==========================================:
After adding running = false, it's still not working.
before reset
main.js:128 CountDownTimer {duration: 25, granularity: 1000, tickFtns: Array[0], running: true, resetFlag: false}
main.js:129 after reset
main.js:131 CountDownTimer {duration: 25, granularity: 1000, tickFtns: Array[0], running: true, resetFlag: true}
calling start
main.js:64 Reset inside closure
It seems that there's some lag after resetting the timer? (The reset inside closure suppposed to appear before the after reset.
Related
I am using the solution in this answer to create an accurate javascript timer. The code works fine. But I want it to have a fixed interval option. like it need to output 100, 200, 300, so on..,
Math.round(timer.getTime() / 1000); this code rounds the value to the nearest second so timer goes 1, 2, 3, 4, 5...
I tried adjusting the duration of setInterval to 50 and rounding to nearest 100, it works almost fine to my needs. but it is repeating numbers and sometimes skips few numbers.
And also I need some timer to start from a specific number, say from 400 to 10000. the class has 0 as default. How do I go about implementing that?
please find the codepen for more code and details:
https://codepen.io/gurgoon32/pen/KKzYYKG
class Timer {
constructor() {
this.isRunning = false;
this.startTime = 0;
this.overallTime = 0;
}
_getTimeElapsedSinceLastStart() {
if (!this.startTime) {
return 0;
}
return Date.now() - this.startTime;
}
start() {
if (this.isRunning) {
return console.error('Timer is already running');
}
this.isRunning = true;
this.startTime = Date.now();
}
stop() {
if (!this.isRunning) {
return console.error('Timer is already stopped');
}
this.isRunning = false;
this.overallTime = this.overallTime + this._getTimeElapsedSinceLastStart();
}
reset() {
this.overallTime = 0;
if (this.isRunning) {
this.startTime = Date.now();
return;
}
this.startTime = 0;
}
getTime() {
if (!this.startTime) {
return 0;
}
if (this.isRunning) {
return this.overallTime + this._getTimeElapsedSinceLastStart();
}
return this.overallTime;
}
}
let the_interval;
function round_nearest_hundred(num) {
return Math.round(num / 100) * 100;
}
function onUpdateTimer(duration) {
const timeInSeconds = Math.round(timer.getTime() / 1000);
document.getElementById('time').innerText = timeInSeconds;
document.getElementById('accTime').innerText = round_nearest_hundred(timer.getTime());
console.log(round_nearest_hundred(timer.getTime()));
if (round_nearest_hundred(timer.getTime()) >= duration) {
document.getElementById('status').innerText = 'complete';
timer.stop();
timer_manager(false);
}
}
function timer_manager(flag, updateFunction, time, duration) {
if (flag) {
the_interval = setInterval(function() {
updateFunction(duration);
}, time);
} else {
clearInterval(the_interval);
}
}
const timer = new Timer();
//timer.start();
timer_manager(true, onUpdateTimer, 50, 10000);
document.getElementById('start').addEventListener('click', function() {
timer.start();
});
document.getElementById('stop').addEventListener('click', function() {
timer.stop();
});
document.getElementById('restart').addEventListener('click', function() {
timer_manager(true, onUpdateTimer, 100, 10000);
timer.reset();
timer.start();
});
<p>Elapsed time: <span id="time">0</span>s</p>
<p id="accTime"></p>
<p id="status"></p>
<button id="start">start</button>
<button id="stop">pause</button>
<button id="restart">restart</button>
Give this a try:
class Timer {
constructor () {
this.isRunning = false;
this.startTime = 0;
this.overallTime = 0;
}
_getTimeElapsedSinceLastStart () {
if (!this.startTime) {
return 0;
}
return Date.now() - this.startTime;
}
start () {
if (this.isRunning) {
return console.error('Timer is already running');
}
this.isRunning = true;
this.startTime = Date.now();
}
stop () {
if (!this.isRunning) {
return console.error('Timer is already stopped');
}
this.isRunning = false;
this.overallTime = this.overallTime + this._getTimeElapsedSinceLastStart();
}
reset () {
this.overallTime = 0;
if (this.isRunning) {
this.startTime = Date.now();
return;
}
this.startTime = 0;
}
getTime () {
if (!this.startTime) {
return 0;
}
if (this.isRunning) {
return this.overallTime + this._getTimeElapsedSinceLastStart();
}
return this.overallTime;
}
}
let the_interval;
function round_nearest_hundred(num){
return Math.floor(num / 100)*100;
}
function onUpdateTimer(start, duration){
const startTime = timer.getTime() + start;
const timeInSeconds = Math.floor(timer.getTime() / 1000);
document.getElementById('time').innerText = timeInSeconds;
document.getElementById('accTime').innerText = round_nearest_hundred(startTime);
console.log(round_nearest_hundred(startTime));
if(round_nearest_hundred(timer.getTime()) >= (duration - start)){
document.getElementById('status').innerText = 'complete';
timer.stop();
timer_manager(false);
}
}
function timer_manager(flag, updateFunction, time, start, duration){
if(flag){
the_interval = setInterval(function(){updateFunction(start, duration);}, time);
} else {
clearInterval(the_interval);
}
}
const timer = new Timer();
//timer.start();
timer_manager(true, onUpdateTimer, 50, 1000, 10000);
document.getElementById('start').addEventListener('click', function(){
timer.start();
});
document.getElementById('stop').addEventListener('click', function(){
timer.stop();
});
document.getElementById('restart').addEventListener('click', function(){
timer_manager(false);
timer_manager(true, onUpdateTimer, 100, 0, 10000);
timer.reset();
timer.start();
});
<p>Elapsed time: <span id="time">0</span>s</p>
<p id="accTime"></p>
<p id="status"></p>
<button id="start">start</button>
<button id="stop">pause</button>
<button id="restart">restart</button>
Math.round() is a little confusing in this context because it means 500ms rounds up to 1s, making you think you've reached that time before you really have. It's better to use Math.floor() (rounds down) so that you only see the number of seconds that have really elapsed. I think this should solve the skipping issue.
In the Reset function, it's good practice to clear the last interval before setting a new one. It seems that otherwise you would be running two setInterval functions, with only the latest one being referred to by variable the_interval.
To start from a specific number, I've added an argument (start) to the timer_manager function. This gets passed to the onUpdateTimer function, because that is where your logic decides if the timer has finished or not (clearly, that would depend on which value it started from). Finally, also in that function, it's up to you whether you want to display to the user the actual number of seconds elapsed (e.g. start: 1s, end: 10s, elapsed: 9s), or that plus the starting point (e.g. start: 1s, end: 10s, elapsed: 10s).
In order to provide a start time value, you simply have to modify the constructor so that it accepts the start time as a parameter:
class Timer {
constructor (startTime = 0) {
this.isRunning = false;
this.startTime = startTime;
this.overallTime = startTime;
}
// ...
}
const timer1 = new Timer(); // timer1 will start from 0
const timer2 = new Timer(500); // timer2 will start from 500
For what concerns the interval, if you want to display hundredths of seconds rounded to hundreds (e.g. 100, 200, 300, ...), you have to set the interval time to 10ms and use the function "round_nearest_hundred()" you already have:
// ...
function onUpdateTimer(duration) {
//const timeInSeconds = Math.round(timer.getTime() / 1000);
//document.getElementById('time').innerText = timeInSeconds;
const timeInHundredthsOfSeconds = round_nearest_hundred(timer.getTime());
document.getElementById('time').innerText = HundredthsOf;
document.getElementById('accTime').innerText = round_nearest_hundred(timer.getTime());
console.log(round_nearest_hundred(timer.getTime()));
if (round_nearest_hundred(timer.getTime()) >= duration) {
document.getElementById('status').innerText = 'complete';
timer.stop();
timer_manager(false);
}
}
// ...
timer_manager(true, onUpdateTimer, 10, 10000);
// ...
I wrote this code that starts a timer. I fire a function that restarts the timer when it reaches 0. It works, but I get an error in the console that says Uncaught TypeError: Cannot read property 'restartTimer' of undefined. It has to do with this.restartTimer();
timer = utility.math.surveyTimer({
seconds: time,
onUpdateStatus: function(remainingTime) {
$(surveyTimerNode).text(remainingTime);
},
restartTimer: function() {
window.TimerInterval = timer.start();
},
onCounterEnd: function() {
if (utility.bool.isQuestionScreen()) {
if (utility.bool.surveyWillLoop()) {
data.setPersistentSurveyData('DSM_SURVEY_SCREENS', surveyScreens);
data.setPersistentSurveyData('DSM_SURVEY_SCREEN_ORDER', surveyScreenOrder);
tagData = data.getPersistentSurveyData('DSM_SURVEY_DATA');
apiParam = api.helper.buildAPIParam('surveyTimeout', tagData);
api.post.postToAPI(apiParam);
parent.resetSurveyProgress();
parent.moveToNextScreen();
this.restartTimer();
} else {
parent.goToEndscreen();
}
}
}
});
window.TimerInterval = timer.start();
No errors in JSLint, just errors on run. What's so bizarre is that it works, the timer does reset. How do I remove this error?
Here's the function that actually does the timer counting:
this.surveyTimer = function (options) {
var timer,
instance = this,
minutes,
secondsMinusMinutes,
remainingTime,
seconds = options.seconds || 30,
updateStatus = options.onUpdateStatus || function () {
return undefined;
},
counterEnd = options.onCounterEnd || function () {
return undefined;
};
function zeroPad(n) {
return (n < 10) ? ("0" + n) : n;
}
function decrementCounter() {
minutes = Math.floor(seconds / 60);
secondsMinusMinutes = seconds - minutes * 60;
remainingTime = minutes + ':' + zeroPad(secondsMinusMinutes);
updateStatus(remainingTime);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds -= 1;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
return timer;
};
this.stop = function () {
clearInterval(timer);
};
return this;
};
Just a guess, but I think your use of this in your options object is not the this you think it is...
Try changing your implementation of surveyTimer, where it is currently:
counterEnd();
to:
counterEnd.call(options);
Need some help with my code, I can't get my alerts to work with my countdown timer. They should be alerting at 4,3,2 minutes left on the timer. I currently can't get the alerts to fire at all, sometimes they would fire but each second after 4, the alert for "4" would fire. I need it to just go once... Any help would be appreciated
Heres my script
var running=false
var endTime=null
var timerID=null
function startTimer(){
running=true
now=new Date()
now=now.getTime()
endTime=now+(1000*60*5)
showCountDown()
}
function showCountDown(){
var now=new Date()
now=now.getTime()
if (endTime-now<=239990 && endTime-now>240010){alert("4")};
if (endTime-now<=179990 && endTime-now>180010){alert("3")};
if (endTime-now<=119990 && endTime-now>120010){alert("2")};
if (endTime-now<=0){
stopTimer()
alert("Time is up. Put down pencils")
} else {
var delta=new Date(endTime-now)
var theMin=delta.getMinutes()
var theSec=delta.getSeconds()
var theTime=theMin
theTime+=((theSec<10)?":0" : ":")+theSec
document.forms[0].timerDisplay.value=theTime
if (running){
timeID=setTimeout("showCountDown()",1000)
}
}
}
function stopTimer(){
clearTimeout(timeID)
running=false
document.forms[0].timerDisplay.value="0.00"
}
Update, Sorry meant minutes instead of seconds
Update 2: Change the ifs, now they fire but keep firing after the 4 second mark
if (endTime-now<=240010 && endTime-now<=239990){alert("4")};
if (endTime-now<=180010 && endTime-now<=179990){alert("3")};
if (endTime-now<=120010 && endTime-now<=119990){alert("2")};
Why are you calling clearTimeout? setTimeout invokes its callback only once. There is no need to clear it. Also you could just have a variable that stores the minutes until the end of the countdown and decrement that by one in each iteration.
The simplest solution might look like this
function startTimer(minutesToEnd) {
if(minutesToEnd > 0) {
if(minutesToEnd <= 4) {
console.log(minutesToEnd);
}
setTimeout(startTimer, 60000, minutesToEnd - 1);
} else {
console.log("Time is up. Put down pencils")
}
}
I actually spent some time working on this. I have no idea if this is what you wanted, but I created a timer library. I have a working demo for you. I had fun making this. Let me know what you think:
JS:
(function () {
var t = function (o) {
if (!(this instanceof t)) {
return new t(o);
}
this.target = o.target || null;
this.message = o.message;
this.endMessage = o.endMessage;
//setInterval id
this.si = -1;
//Initial start and end
this.startTime = null;
this.endTime = null;
this.interTime = null;
this.duration = o.duration || 1000 * 60 * 5;
//looping speed miliseconds it is best to put the loop at a faster speed so it doesn't miss out on something
this.loop = o.loop || 300;
//showing results miliseconds
this.show = o.show || 1000;
};
t.fn = t.prototype = {
init: function () {}
};
//exporting
window.t = t;
})();
//Timer Functions ---
t.fn.start = function () {
this.startTime = new Date();
this.interTime = this.startTime.getTime();
this.endTime = new Date().setMilliseconds(this.startTime.getMilliseconds() + this.duration);
//returns undefined... for some reason.
console.log(this.endTime);
var $this = this;
this.writeMessage(this.duration);
this.si = setInterval(function () {
var current = new Date(),
milli = current.getTime();
if (milli - $this.interTime >= $this.show) {
var left = $this.endTime- milli;
if (left <= 0) {
$this.stop();
} else {
$this.interTime = milli;
$this.writeMessage(left);
}
}
}, this.loop);
return this;
};
t.fn.writeMessage = function(left){
this.target.innerHTML = this.message + ' ' + Math.floor(left / 1000);
return this;
};
t.fn.stop = function () {
//stopping the timer
clearInterval(this.si);
this.target.innerHTML = this.endMessage;
return this;
};
//Not chainable
t.fn.isRunning = function () {
return this.timer > -1;
};
var timer = t({
target: document.getElementById('results'),
loop: 50,
duration: 10000,
show: 1000, //default is at 1000 miliseconds
message: 'Time left: ', //If this is ommited then only the time left will be shown
endMessage: 'Time is up. Put down your pencils'
}).start();
document.getElementById('stop').onclick = function(){
timer.stop();
};
HTML:
<div id="results"></div>
<button id="stop">Stop</button>
Demo here
Update: I added some stuff
Demo 2
Update 2: I fixed the bug where 10 would hop straight to 8
Demo 3
window.setInterval(function(){
//do stuff
}, milisec);
Is there a way to stop this interval at will, and to resume it from where it lasted? Say, code runs every 5 sec. I stop it in the middle of the 2nd second, when resumed, I want it to run the remaining 3 seconds and continue to run afterwards every 5 sec. again.
Try this:
1- when you want to pause the timer, calculate the remaining milliseconds and store it somewhere then call clearInterval.
2- When you want to resume the timer, just make a call to setTimeout passing the remaining time stored in the previous step as the argument.
3- And in setTimeout's callback you should call setInterval again.
UPDATE: This is what you want, a changed version of javascript: pause setTimeout(); thanks to #Felix Kling
function IntervalTimer(callback, interval) {
var timerId, startTime, remaining = 0;
var state = 0; // 0 = idle, 1 = running, 2 = paused, 3= resumed
this.pause = function () {
if (state != 1) return;
remaining = interval - (new Date() - startTime);
window.clearInterval(timerId);
state = 2;
};
this.resume = function () {
if (state != 2) return;
state = 3;
window.setTimeout(this.timeoutCallback, remaining);
};
this.timeoutCallback = function () {
if (state != 3) return;
callback();
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
};
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
}
Usage:
var timer = new IntervalTimer(function () {
alert("Done!");
}, 5000);
window.setTimeout(function () {
timer.pause();
window.setTimeout(function () {
timer.resume();
}, 5000);
}, 2000);
To piggyback off Alireza's answer, here's an ES6 class that does the same thing with a bit more functionality, and doesn't start right away. You can set a maximum number of times the timer will fire off before automatically stopping, and pause and resume any number of times before the next time it's set to fire off.
export default class IntervalTimer{
constructor(name, callback, interval, maxFires = null){
this.remaining = 0;
this.state = 0; // 0 = idle, 1 = running, 2 = paused, 3= resumed
this.name = name;
this.interval = interval; //in ms
this.callback = callback;
this.maxFires = maxFires;
this.pausedTime = 0; //how long we've been paused for
this.fires = 0;
}
proxyCallback(){
if(this.maxFires != null && this.fires >= this.maxFires){
this.stop();
return;
}
this.lastTimeFired = new Date();
this.fires++;
this.callback();
}
start(){
this.log.info('Starting Timer ' + this.name);
this.timerId = setInterval(() => this.proxyCallback(), this.interval);
this.lastTimeFired = new Date();
this.state = 1;
this.fires = 0;
}
pause(){
if (this.state != 1 && this.state != 3) return;
this.log.info('Pausing Timer ' + this.name);
this.remaining = this.interval - (new Date() - this.lastTimeFired) + this.pausedTime;
this.lastPauseTime = new Date();
clearInterval(this.timerId);
clearTimeout(this.resumeId);
this.state = 2;
}
resume(){
if (this.state != 2) return;
this.pausedTime += new Date() - this.lastPauseTime;
this.log.info(`Resuming Timer ${this.name} with ${this.remaining} remaining`);
this.state = 3;
this.resumeId = setTimeout(() => this.timeoutCallback(), this.remaining);
}
timeoutCallback(){
if (this.state != 3) return;
this.pausedTime = 0;
this.proxyCallback();
this.start();
}
stop(){
if(this.state === 0) return;
this.log.info('Stopping Timer %s. Fired %s/%s times', this.name, this.fires, this.maxFires);
clearInterval(this.timerId);
clearTimeout(this.resumeId);
this.state = 0;
}
//set a new interval to use on the next interval loop
setInterval(newInterval){
this.log.info('Changing interval from %s to %s for %s', this.interval, newInterval, this.name);
//if we're running do a little switch-er-oo
if(this.state == 1){
this.pause();
this.interval = newInterval;
this.resume();
}
//if we're already stopped, idle, or paused just switch it
else{
this.interval = newInterval;
}
}
setMaxFires(newMax){
if(newMax != null && this.fires >= newMax){
this.stop();
}
this.maxFires = newMax;
}
}
You should only need setTimeout with a go and stop - http://jsfiddle.net/devitate/QjdUR/1/
var cnt = 0;
var fivecnt = 0;
var go = false;
function timer() {
if(!go)
return;
cnt++;
if(cnt >= 5){
cnt=0;
everyFive();
}
jQuery("#counter").text(cnt);
setTimeout(timer, 1000);
}
function everyFive(){
fivecnt++;
jQuery("#fiver").text(fivecnt);
}
function stopTimer(){
go = false;
}
function startTimer(){
go = true;
timer();
}
let time = document.getElementById("time");
let stopButton = document.getElementById("stop");
let playButton = document.getElementById("play");
let timeCount = 0,
currentTimeout;
function play_pause() {
let status = playButton.innerHTML;
if (status == "pause") {
playButton.innerHTML = "Resume";
clearInterval(currentTimeout);
return;
}
playButton.innerHTML = "pause";
stopButton.hidden = false;
clearInterval(currentTimeout);
currentTimeout = setInterval(() => {
timeCount++;
const min = String(Math.trunc(timeCount / 60)).padStart(2, 0);
const sec = String(Math.trunc(timeCount % 60)).padStart(2, 0);
time.innerHTML = `${min} : ${sec}`;
}, 1000);
}
function reset() {
stopButton.hidden = true;
playButton.innerHTML = "play";
clearInterval(currentTimeout);
timeCount = 0;
time.innerHTML = `00 : 00`;
}
<div>
<h1 id="time">00 : 00</h1>
<br />
<div>
<button onclick="play_pause()" id="play">play</button>
<button onclick="reset()" id="stop" hidden>Reset</button>
</div>
</div>
I got this function that starts a timer on this format 00:00:00 whenever I click on a button. But I don't know how to do functions resume and pause. I've found some snippets that I thought could be helpful but I couldn't make those work. I'm new to using objects in js.
function clock() {
var pauseObj = new Object();
var totalSeconds = 0;
var delay = setInterval(setTime, 1000);
function setTime() {
var ctr;
$(".icon-play").each(function () {
if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_');
});
++totalSeconds;
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds / 3600)));
$("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds / 60) % 60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60)));
}
}
pad() just adds leading zeros
I think it will be better if you will create clock object. See code (see Demo: http://jsfiddle.net/f9X6J/):
var Clock = {
totalSeconds: 0,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(Math.floor(self.totalSeconds / 3600));
$("#min").text(Math.floor(self.totalSeconds / 60 % 60));
$("#sec").text(parseInt(self.totalSeconds % 60));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
};
Clock.start();
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
Just clearing the interval wouldn't work, because totalSeconds would not get incremented.
I would set up a flag that determines if the clock is paused or not.
This flag would be simply set upon calling pause() or unset upon resume().
I separated the totalSeconds increase to a 'tick' timeout that will always be running, even when paused (so that we can keep track of the time when we resume).
The tick function will therefore only update the time if the clock is not paused.
function clock()
{
var pauseObj = new Object();
var totalSeconds = 0;
var isPaused = false;
var delay = setInterval(tick, 1000);
function pause()
{
isPaused = true;
}
function resume()
{
isPaused = false;
}
function setTime()
{
var ctr;
$(".icon-play").each(function(){
if( $(this).parent().hasClass('hide') )
ctr = ($(this).attr('id')).split('_');
});
$("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600)));
$("#min_" + ctr[1]).text(pad( Math.floor((totalSeconds/60)%60)));
$("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds%60)));
}
function tick()
{
++totalSeconds;
if (!isPaused)
setTime();
}
}
Use window.clearInterval to cancel repeated action which was set up using setInterval().
clearInterval(delay);
<html>
<head><title>Timer</title>
<script>
//Evaluate the expression at the specified interval using setInterval()
var a = setInterval(function(){disp()},1000);
//Write the display() for timer
function disp()
{
var x = new Date();
//locale is used to return the Date object as string
x= x.toLocaleTimeString();
//Get the element by ID in disp()
document.getElementById("x").innerHTML=x;
}
function stop()
{
//clearInterval() is used to pause the timer
clearInterval(a);
}
function start()
{
//setInterval() is used to resume the timer
a=setInterval(function(){disp()},1000);
}
</script>
</head>
<body>
<p id = "x"></p>
<button onclick = "stop()"> Pause </button>
<button onclick = "start()"> Resume </button>
</body>
</html>