Countdown Timer to Add extra 2 minutes - javascript

I have created a countdown timer and am trying to add 2 minutes into the existing timer to extend the timer.
My Code
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
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.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
$(document).ready(function() {
var counter = 0;
var display = document.querySelector('#time'),
//timer = new CountDownTimer(600);
timer = new CountDownTimer(125); // for debug
timer.onTick(format).onTick(restart).start();
function restart() {
if (this.expired()) {
alert("Expired");
}
}
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
alert("Extending Time");
counter++;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span> minutes
I managed to trigger an event that after 2 minutes will show an alert that the time will be extended, but so far, I can't think of any method or functions I can use to add the extra time. Is there any way I can do this?

Add code as following:
CountDownTimer.prototype.reset = function (duration) {
this.duration = duration;
}
and rewrite function format as :
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
//alert("Extending Time");
timer.reset(timer.duration + 120);
counter++;
}
}
}

You can add code in CountDownTimer.prototype.start before setTimeout like:
this.instance = setTimeout(...)
add function:
CountDownTimer.prototype.kill = function() {
clearTimeout(this.instance)
}
call function kill to stop timer permanently.

Related

After button click timer should start again

<script>
var minutes = 1;
var seconds = 45;
$(document).ready(function () {
setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
document.getElementById('next').click();
minutes = 1;
seconds = 45;
}
}
</script>
This is my code for the timer and it should restart after button click whose id is #next. I did many things but it won't work. Please help.
Button Id = Next
Here's my solution to your issue.
I've noticed $(document).ready() so I instantly presumed you are
using jQuery.
var timerInterval is a direct reference to the timer that you started.
To stop the timer, use clearInterval(timerInterval) [Same story goes for setTimeout()].
I've changed your countdown timer because I couldn't be bothered fixing it.
var timerInterval;
let minutes = 2;
let seconds = 42;
let duration = (minutes * 60) + seconds;
let display = document.querySelector('#timer');
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
timerInterval = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
clearInterval(timerInterval);
}
}, 1000);
}
startTimer(duration, display);
$('button').click((e) => {
clearInterval(timerInterval);
startTimer(duration, display);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timer"></span>
<br>
<button>Reset Timer</button>
You should not rely on setInterval (or setTimeout) to calculate a time value. It is not guaranted to be called at the specified interval. I believe in some case it could also be paused by the browser.
You could try something like this :
<span id='timer'></span>
<button id='next'>Next</button>
<script>
var btn = document.getElementById('next');
btn.addEventListener('click', function(e) {
// 10 is the duration in seconds
startNextTimer(10, function() { alert('done!');} );
});
function startNextTimer(numSecondsDuration, callback) {
var label = document.getElementById('timer');
var endDate = new Date();
endDate.setSeconds(endDate.getSeconds() + numSecondsDuration);
var calcTimeLeft = function() { return Math.ceil((endDate - (new Date())) / 1000); };
label.innerHTML = calcTimeLeft() + " secs";
var intervalId = setInterval(function() {
var numSecondsLeft = calcTimeLeft();
if (numSecondsLeft <= 0) {
clearInterval(intervalId);
if (callback) {
callback();
}
}
label.innerHTML = numSecondsLeft + " secs";
}, 500);
}
</script>
Without the html I can't give you step by step but basically, you need to clear the interval before you can restart it.
<script>
var minutes = 1;
var seconds = 45;
var interval_id=setInterval(startTimer, 1000);
$('#next').on("click",function(){
clearInterval(interval_id);
minutes = 1;
seconds = 45;
document.getElementById("timer").innerHTML ="";
interval_id=setInterval(startTimer, 1000);
});
function startTimer() {
document.getElementById("timer").innerHTML = (minutes - 1) + ":" + --seconds;
if (seconds == 0) {
minutes--;
if (minutes != 0) {
seconds = 60;
} else {
seconds = 0;
}
}
if (minutes == 0 && seconds == 0) {
minutes = 1;
seconds = 45;
}
}
</script>

Am working on a timer, Why is the breakCount() function not updating after using setTimeout()?

I want the breakCount function to start counting when the previous session times out, it only updates the variable $breakData but doesn't countdown, why? how can I make it work? If this snippet doesn't help you understand what I mean please say so.
function holdCount() {
var t,
secs = 60,
mins = countSession.innerHTML;
mins--;
function countdown() {
secs--;
if (secs < 0) {
mins--;
secs = 59;
};
if (secs < 10) {
countSession.innerHTML = mins + ':' + '0' + secs;
} else {
countSession.innerHTML = mins + ':' + secs;
};
t = setTimeout(countdown, 1000);
if (mins == 0 && secs == 0) {
clearTimeout(t);
breakCount();
function breakCount() {
var $breakData = $('#displayBreak').text();
$breakData--;
$('#sessionCount').text($breakData);
}
setTimeout(breakCount, 1000);
}
}
countdown();
}
countSession.addEventListener('click', holdCount, false);

clearInterval() not working

Session length is the start time of the timer, default is 25. isEven is used to start/stop the timer, if isEven is false, the timer should start, if it is odd it should hit clearInterval, which for some reason is not stopping execution of tick() function (which counts down the timer).
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
var myVar = setInterval(tick, 1000);
if (isEven == false) {
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--;
seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML =
"0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
clearInterval(myVar);
}
};
Move the tick() function declaration outside of the if block
setInterval variable is a local one. So its value is overwritten every time you call countdown
. The solution would be to initialize myVar outside the function countdown or to make it a global variable like this :
window.myVar =setInterval (tick,1000);
You have also to put this instruction in the first if block, so that it is not overwritten everytime
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
if (isEven == false) {
window.myVar = setInterval(tick, 1000);
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--; seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML = "0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
if (window.myVar){
clearInterval(window.myVar);
window.myVar = null;
}
}
};

How to add a pause/play function to a running setInterval?

So I am trying to create a pomodoro timer. The website currently looks and functions like this: POMODOROone
My timer is counting down correctly so far. However, when I try to add a pause and resume functionality, it breaks. I have tried multiple ways but I haven't had much success. So I removed all my attempts and I have the code for what is working so far.
So, my question is how would I add a pause/resume functionality to my timer? Also, how would I make my timer stop when I click on any of the positive and negative spans or the inputs?
Here is the Javascript:
//decreases break time by 5 mins
function decreaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases break time by 5 mins
function increaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//decreases session time by 5 mins
function decreaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases session time by 5 mins
function increaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//countdown timer
function start() {
var sec = 60;
var timerParagraph = document.getElementById("timerParagraph").innerHTML;
var min = timerParagraph.substring(0, timerParagraph.indexOf(":"));
var time = min * 60;
min = parseInt(min,10)-1;
setInterval(function() {
sec = sec - 1;
if (sec < 0) {
min -= 1;
sec = 59;
}
if (min < 0 && sec < 0) {
clearInterval(start());
}
var temp;
if (min.toString().length == 1 && sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + sec;
} else if (sec.toString().length == 1 && min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = min + ":" + "0" + sec;
} else if (min.toString().length == 1 && sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + "0" + sec;
} else {
document.getElementById("timerParagraph").innerHTML = min + ":" + sec;
}
},1000);
}
New Updated Code:
//decreases break time by 5 mins
function decreaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("breakInput").value = new_time;
clearInterval(timer);
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases break time by 5 mins
function increaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
timer = null;
}
//decreases session time by 5 mins
function decreaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
}
//increases session time by 5 mins
function increaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
}
//countdown timer
var timer = null;
var sec = 60;
function start() {
var timerParagraph = document.getElementById("timerParagraph").innerHTML;
var min = timerParagraph.substring(0, timerParagraph.indexOf(":"));
min = parseInt(min,10)-1;
function onTimer() {
sec = sec - 1;
if (sec < 0) {
min -= 1;
if (min == 0 && sec == 0) {
// When min and second equals zero, timer stops
clearInterval(timer);
}
sec = 59;
}
if (min.toString().length == 1 && sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + sec;
} else if (sec.toString().length == 1 && min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = min + ":" + "0" + sec;
} else if (min.toString().length == 1 && sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + "0" + sec;
} else {
document.getElementById("timerParagraph").innerHTML = min + ":" + sec;
}
}
timer = setInterval(onTimer,1000);
console.log("Start timer");
// when the div is clicked, the timer starts and stops.
document.getElementById("timerDiv").onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
} else {
timer = setInterval(onTimer,1000);
console.log("Resume timer");
}
}
}
This updated code works for the following new actions:
1. When the timer starts playing, and if the timerDiv is clicked, it will pause.
2. And when clicked again, it will resume.
Now, when I click on the positive and negative signs and change the time, it changes the time like it should and clears the interval like it is called. However, when I click on the timerDiv again, instead of playing from the start, it resumes playing the time from where it left off. How would I make it so that when I click on the timerDiv again, it counts down from the new time instead of resuming previous time.
Here is an implementation called interruptible-timer:
// A timer which can be interrupted and picks up where you left off.
//
// Usage:
// ```
// var timer = interruptibleTimer(task, 5000);
// timer.start(); // Start the timer, or resume it after stopping.
// timer.stop(); // Timer continues to run, but task will not be called.
// timer.run(); // Run task now, and start timer again from now.
// timer.reset(); // Stop the timer and reset it to 0.
// ```
var set = window.setTimeout;
var clear = window.clearTimeout;
function interruptibleTimer(fn, interval) {
var recent = 0;
var timer;
// PRIVATE FUNCTIONS
function now() { return +new Date(); }
function delay() { return recent ? Math.max(0, recent + interval - now()) : interval; }
function schedule() { timer = set(run, delay()); }
// PUBLIC APIs
function start() { if (!timer) schedule(); }
function stop() { clear(timer); timer = 0; }
function run() { fn(); recent = now(); schedule(); }
function reset() { stop(); recent = 0; }
return {start, stop, run, reset};
}
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval
The way you set your interval and clear it inside of the start() function doesn't make much sense and is probably the cause of your troubles.
The function called every second should be stored with a function name.
/*
A wrapper variable is used to keep variables in scope so clearinterval can be used and variables don't interact outside of 'T'.
*/
var T = {
sec: null,
timerParagraph: null,
min: null,
time: null,
interval: null,
//countdown timer
start: function(){
T.interval = setInterval(T.tickClock,1000);
},
pause: function(){
clearInterval(T.interval);
},
reset: function(){
T.sec = 60;
T.timerParagraph = document.getElementById("timerParagraph").innerHTML;
T.min = T.timerParagraph.substring(0, T.timerParagraph.indexOf(":"));
T.time = T.min * 60;
T.min = parseInt(T.min,10)-1;
},
tickClock: function(){
T.sec = T.sec - 1;
if (T.sec < 0) {
T.min -= 1;
T.sec = 59;
}
if (T.min < 0 && T.sec < 0) {
clearInterval(T.interval);
}
if (T.min.toString().length == 1 && T.sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + T.min + ":" + T.sec;
} else if (T.sec.toString().length == 1 && T.min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = T.min + ":" + "0" + T.sec;
} else if (T.min.toString().length == 1 && T.sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + T.min + ":" + "0" + T.sec;
} else {
document.getElementById("timerParagraph").innerHTML = T.min + ":" + T.sec;
}
}
/*
Use T.reset() to set the clock back to the beginning. Use T.start to begin the interval and T.pause to stop the interval.
You may need to record how far within a second the pause is used so you can offset the second when you start again.
This would mean having a settimeout which counts in milliseconds or something.
*/
}
I haven't tested this code so beware of potential typos, although I did double check for those.
To make the timer pause use onclick="T.pause()" within the elements you want to have that functionality.
Or within javascript using
element.onclick = function(){
T.pause();
}
http://www.w3schools.com/jsref/event_onclick.asp

Java script Timer CountDown

I'm creating java script count down timer and it works up to 60 seconds correctly and after that its not working.
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
debugger;
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
When i run this program this start 1:59 and it continues up to 1:01. after that this display value rest to 1:59. (not 0:59). what i did wrong in here?
Fiddle demo is in Here: in here you can see two values are blinking each other
Here's how I'd implement this. Hopefully the comments are sufficient. It needs an element in the page with ID "counterDiv" to write the values to.
function quickCount(mins) {
// Keep some values in a closure
var el = document.getElementById('counterDiv');
var secs = 0;
// Helper to pad single digit numbers
function z(n){return (n<10? '0':'') + n}
// Keep a reference to the interval
var timer = setInterval(function() {
// Write the values
el.innerHTML = mins + ':' + z(secs);
// Decremement seconds
--secs;
// If finished a minute, decrement minut
if (secs < 0) {
if (mins) {
--mins;
secs = 59;
// If finsihed minutes too, cancel timer
} else {
timer && clearInterval(timer);
}
}
// Run at about every second
}, 1000);
}
window.onload = function() {
quickCount(2);
}
HTH
<head>
<script type="text/javascript">
function timer()
{
var val = document.getElementById("LabelTimer");
if (val !== null)
{
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes)
{
var seconds = 60;
var mins = minutes;
function tick()
{
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1;
seconds--;
var t=current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
counterVal.value = t;
var result = counterVal.innerHTML;
if (result === "0:00")
{
CloseIdlePage();
}
if (seconds > 0)
{
setTimeout(tick, 1000);
}
else
{
if (mins > 1)
{
countdown(mins - 1);
}
}
}
tick();
}
</script>
</head>
<body>
<div>TODO write content</div>
<input type="text" id="LabelTimer" value="yooo">
<input type="text" id="lblCountDown">
<input type="button" value="try" onclick="timer();" />
</body>
I resolved this as follows:
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
var IsFunctionCalled = false;
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
if (IsFunctionCalled == false) {
IsFunctionCalled = true
countdown(parseInt(PopUpTimeDuration));
}
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
// tick()
} else {
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
See here for Demo

Categories

Resources