How do I resume the countdown timer? - javascript

I am working on a pomodoro clock project where the user can set a session length and a break length so the clock will count down until the user click Stop.
I want the timer to resume after being paused whenever I click Start, but it keeps switching to the other session/break.
I know that I need to calculate the remaining seconds at the time when it stops and then run the startTimer() again.But I haven't been able to figure it out yet.
Any help appreciated! You can scroll down to the //====VIEW====//: startTimer(seconds) to see the logic from there.
Here's my code:
//======MODEL======//
//by default, session lasts 25min, break lasts 5 min
var data = {
session: 25,
break: 5,
isSession: true
}
//===== OCTOPUS=====//
var octopus = {
init: function() {
//initialize the views
settings.init();
timer.init();
},
//========== SETTINGS==========//
//get the time of session and break
getCurrentSession: function() {
return data.session;
},
getCurrentBreak: function() {
return data.break;
},
// set the currently-selected time to the object passed in
setCurrentSession: function(isSession) {
data.isSession = isSession;
},
//increment or decrement the counter
incrementSessionCounter: function() {
data.session++;
settings.render();
},
incrementBreakCounter: function() {
data.break++;
settings.render();
},
decrementSessionCounter: function() {
data.session--;
settings.render();
},
decrementBreakCounter: function() {
data.break--;
settings.render();
}
}
//----- VIEW----//
var settings = {
init: function() {
//display the default session and break with increment and decrement
//listen to click function on either + or - to adjust the timer
this.session = document.getElementById("displaySession");
this.break = document.getElementById("displayBreak");
this.incrementSession = document.getElementById("increaseSession");
this.decrementSession = document.getElementById("decreaseSession");
this.incrementBreak = document.getElementById("increaseBreak");
this.decrementBreak = document.getElementById("decreaseBreak");
this.incrementSession.addEventListener("click", function() {
octopus.incrementSessionCounter();
});
this.decrementSession.addEventListener("click", function() {
octopus.decrementSessionCounter();
});
this.incrementBreak.addEventListener("click", function() {
octopus.incrementBreakCounter();
});
this.decrementBreak.addEventListener("click", function() {
octopus.decrementBreakCounter();
});
this.render();
},
render: function() {
// update the DOM elements with values from the current session and break
var currentSession = octopus.getCurrentSession();
var currentBreak = octopus.getCurrentBreak();
this.session.textContent = currentSession;
this.break.textContent = currentBreak;
}
}
var timer = {
init: function() {
this.startTimer = document.getElementById("start");
this.stopTimer = document.getElementById("stop");
this.nextTimer = document.getElementById("next");
this.render();
},
render: function() {
var displayTimer = document.getElementById("countdown-timer");
this.startTimer.addEventListener("click", function() {
getDeadline();
});
this.nextTimer.addEventListener("click", function() {
getDeadline();
});
this.stopTimer.addEventListener("click", function() {
clearInterval(interval);
delete interval;
})
let interval;
//this function takes in the number of seconds and calculate the seconds left to reach the deadline
function startTimer(seconds) {
const now = Date.now();
const then = now + seconds * 1000;
interval = setInterval(function() {
const secondsLeft = (then - Date.now()) / 1000;
if (secondsLeft < 0) {
clearInterval(interval);
getDeadline();
return;
}
displayTimeLeft(secondsLeft);
}, 1000)
}
//this function takes in the number of leftover secs, convert it into mm:ss and display it on screen
function displayTimeLeft(seconds) {
var minutes = Math.floor(seconds / 60);
var remainderSeconds = Math.round(seconds % 60);
if (remainderSeconds < 10) {
var display = `${minutes}: 0${remainderSeconds}`;
} else
var display = `${minutes}: ${remainderSeconds}`;
displayTimer.textContent = display;
}
//this function gets the input from data, depending on session or break
function getDeadline() {
clearInterval(interval);
var time_input;
if (data.isSession) {
time_input = octopus.getCurrentSession();
} else {
time_input = octopus.getCurrentBreak();
}
data.isSession = !data.isSession;
startTimer(time_input * 60);
}
}
}
octopus.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- View 1: the settings contain session length and break length-->
<section>
<div id="session">
<button type="button" id="increaseSession">+</button>
<span id="displaySession">25</span>
<button type="button" id="decreaseSession">-</button>
</div>
<div id="break">
<button type="button" id="increaseBreak">+</button>
<span id="displayBreak">5</span>
<button type="button" id="decreaseBreak">-</button>
</div>
<div><button id="start">START</button>
<button id="next">NEXT</button>
<button id="stop">STOP</button></div>
</section>
<!--View 2: the timer itself-->
<div id="countdown-timer"></div>

Related

Alert returning as undefined

I am trying to have my alert show up with the time that my timer shows.
function Stopwatch(elem) {
var time = 0;
var offset;
var interval;
function update() {
if (this.isOn) {
time += delta();
}
elem.textContent = timeFormatter(time);
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = now;
return timePassed;
}
function timeFormatter(time) {
time = new Date(time);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
var milliseconds = time.getMilliseconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
while (milliseconds.length < 3) {
milliseconds = '0' + milliseconds;
}
return minutes + ' : ' + seconds + ' . ' + milliseconds;
}
this.start = function() {
interval = setInterval(update.bind(this), 10);
offset = Date.now();
this.isOn = true;
};
this.stop = function() {
clearInterval(interval);
interval = null;
this.isOn = false;
};
this.reset = function() {
time = 0;
update();
};
this.isOn = false;
}
var timer = document.getElementById('timer');
var toggleBtn = document.getElementById('toggle');
var resetBtn = document.getElementById('reset');
var watch = new Stopwatch(timer);
function start() {
toggleBtn.textContent = 'Stop';
watch.start();
}
function stop() {
toggleBtn.textContent = 'Start';
watch.stop();
}
toggleBtn.addEventListener('click', function() {
watch.isOn ? stop() : start();
});
resetBtn.addEventListener('click', function() {
watch.reset();
});
function alertSystem(){
var timer = document.getElementById('timer')
alert(timer);
}
<h1 id="timer">00 : 00 . 000</h1>
<div>
<button class=button id="toggle">Start</button>
<button class=button id="reset">Reset</button>
<button onclick='alertSystem()'>get number</button>
</div>
It's a lot of code, but it is mostly to get the timer working. The last function called alertSystem() is on the bottom and is the one that triggers the alert call. For me the alert shows up as [object HTMLHeadingElement] or as undefined. The former comes up when I have alert(timer); but if I do alert(timer.value); or alert(timer.length); I get the latter.
Does anyone know how I can just get the value of the timer in the alert?
To get the timer's value, you should do something like:
document.querySelector('#timer').innerHTML
Otherwise , document.getElementById returns a full element as a js object.

clearinterval() outside of jquery plugin

I create plugin something like this
timer plugin
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.getTimer();
}, 1000);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
and I call the plugin like this.
$(".myTimer").timer({
seconds : 100
});
i called the plugin at timerpage.php. When i changed the page to xxx.php by clicking another menu, the timer interval is still running and i need to the clear the timer interval.
i created a webpage using jquery ajax load. so my page was not refreshing when i change to another menu.
my question is, how to clear the timer interval or destroy the plugin when i click another menu?
Please try with following modifications:
timer plugin:
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.setTimer();
}, 1000);
$this.data("timerIntvalReference", timerIntval); //saving the timer reference for future use
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
Now in some other JS code which is going to change the div content
var intervalRef = $(".myTimer").data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef); //clear the old interval reference
//code to change the div content on menu change
For clearing timer associated with multiple DOM element, you may check below code:
//iterate ovel all timer element:
$("h3[class^=timer]").each(function(){
var intervalRef = $(this).data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef);
});
Hope this will give an idea to deal with this situation.
Instead of var timerIntval; set the variable timerInterval on the window object, then you will have the access this variable until the next refresh.
window.timerIntval = setInterval(function() {
Then when the user clicks on any item menu you can clear it:
$('menu a').click(function() {
clearInterval(window.timerIntval);
});
Live example (with multiple intervals)
$('menu a').click(function(e) {
e.preventDefault();
console.log(window.intervals);
for (var i = 0; i < window.intervals.length; i++) {
clearInterval(window.intervals[i]);
}
});
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
if (!window.intervals) {
window.intervals = [];
}
var intervalId = -1;
var seconds = options.seconds;
var $this = $(this);
var Timer = {
setTimer : function() {
clearInterval(intervalId);
if(seconds <= 0) {
alert("timeout");
} else {
intervalId = setInterval(function(){
//Timer.getTimer();
return Timer.getTimer();
}, 1000);
window.intervals.push(intervalId);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
$(".myTimer").timer({
seconds : 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<menu>
Menu 1
</menu>
<div class="myTimer"></div>
<div class="myTimer"></div>
Just notice that it's little bit risky because you can only run it once otherwise the interval id of the second will override the first.

Closure in timer countdown javascript

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.

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.
I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
stoppedElement.innerHTML = "Mouse stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
stoppedElement.innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 300);
});
//keypress code
var keysElement = document.getElementById('keyPressed');
window.addEventListener("keyup", function() {
buttonPressed = false;
keysElement.innerHTML = "Keys not Pressed";
clearTimeout(timer);
timer = setTimeout("keysPressed", 300);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
keysElement.innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout("keyPressed", 300);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
Here is the HTML code:
<body onload="idleTime()">
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br>
</div>
<div id="idle"></div>
</strong>
</body>
Actually the keysElement and stoppedElement were not referred firing before the DOM load. and also removed the document.write
Thats all all good. :)
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
//document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
//var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
document.getElementById("stopped").innerHTML = "Mouse stopped";
}
function keyStopped() { // the actual function that is called
buttonPressed = false;
document.getElementById("keyPressed").innerHTML = "Keys stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
document.getElementById("stopped").innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 500);
});
window.addEventListener("keyup", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
window.onload = idleTime;
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br></div>
<div id="idle"></div>
</strong>

how do I pause and resume a timer?

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>

Categories