How to change this countdown timer into minutes and seconds? - javascript

Here is my code below, it works fine but I need to change the countdown timer into minutes and seconds. Something like this 59:59 and 09:09 when it's below 10. And thanks so much for the help.
var test = 3600;
$('button').click(function(){
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = test;
}
else {
var value = localStorage.getItem("counter");
}
}
else {
var value = test;
}
$('#divCounter').text(value);
var counter = function() {
if (value == 0) {
localStorage.setItem("counter", test);
value = 0;
}
else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
$('#divCounter').text(value);
};
var interval = setInterval(function() { counter(); }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divCounter">3600</div>
<br>
<button>Start The Counter</button>

One minute = total / 60.
Seconds = total % 60.
Add 0 if minutes or seconds below 10.
Just add this calculations before adding to html.
var test = 3600;
$('button').click(function(){
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = test;
}
else {
var value = localStorage.getItem("counter");
}
}
else {
var value = test;
}
$('#divCounter').text(value);
var counter = function() {
if (value == 0) {
localStorage.setItem("counter", test);
value = 0;
}
else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
var minutes = Math.floor(value / 60)
var seconds = value % 60
if (minutes<10) minutes = '0'+minutes
if (seconds<10) seconds = '0'+seconds
$('#divCounter').text(minutes+':'+seconds);
};
var interval = setInterval(function() { counter(); }, 1000);
});

Related

How can I run 2 counters consecutively with javascript?

I have 1 counter. The counter will count down from 25 first. It will then start counting down from 10 when this time is up. When this time is over, it will start counting down from 25 again. That's how it will go. How can I do it?
var interval10 = 10000;
var interval = 25000;
function tensecond() {
var remaining = interval10 - (Date.now() % interval10);
}
setInterval(function () {
if (remaining >= 100) {
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);
function reset() {
var remaining = interval - (Date.now() % interval);
}
setInterval(function () {
if (remaining >= 100) {
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
tensecond();
}
}, 100);
function millisToMinutesAndSeconds(millis) {
var seconds = Math.floor((millis % 60000) / 1000);
return (seconds < 10 ? "0" : "") + seconds;
}
I'm not entirely sure what you were trying to do in your code. It's easier if you run one interval every second and keep track of which counter you're in and how much time there's left. Like this:
let timeLeft = 25;
let counter = false; // false = 25 sec counter, true = 10 sec counter
setInterval(() => {
if (timeLeft !== 0) return timeLeft--;
if (!counter) {
timeLeft = 10;
counter = true;
// do some more stuff
} else {
timeLeft = 25;
counter = false;
// do some more stuff
}
}, 1000);
Perhaps you had in mind such an implementation?
Each task triggers the following
const interval10 = 1000;
const interval = 2500;
let remaining;
function print(rem, type) {
if (remaining >= rem) {
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
if (type === '25') {
reset()
} else {
tensecond()
}
}
}
function tensecond() {
remaining = interval10 - (Date.now() % interval10);
}
function run25() {
setTimeout(function () {
print(100, '25')
run10()
}, interval);
}
function run10() {
setTimeout(function () {
print(100, '10')
run25()
}, interval10);
}
function reset() {
remaining = interval - (Date.now() % interval);
}
function millisToMinutesAndSeconds(millis) {
const seconds = Math.floor((millis % 60000) / 1000);
return (seconds < 10 ? "0" : "") + seconds;
}
run25();
delete code duplication
The best way to deal with this is to use promises. Each countdown is a promise which resolves once the timer is expired. This way you can chain any number of timers.
SPEED = 100 // set to 1000 to use seconds
function timer(secs, target) {
let endTime = Number(new Date()) + (secs + 1) * SPEED
return new Promise(resolve => {
function step() {
let now = Number(new Date())
if (now >= endTime) {
target.innerText = '0'
return resolve()
}
target.innerText = Math.floor((endTime - now) / SPEED)
window.requestAnimationFrame(step)
}
step()
})
}
async function loop() {
while (1) {
await timer(30, document.querySelector('#a'))
await timer(20, document.querySelector('#b'))
await timer(10, document.querySelector('#c'))
}
}
window.onload = loop
<body style="font-size: 30px">
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
</body>

Countdown Timer to Add extra 2 minutes

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.

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

Jquery Progress Bar: Issue with implementing progress Bar

I'm having a problem with implementing the progress bar using the jquery UI progressbar widget. The actual bar in the widget is not loading in real time. It just jumps to the end bar when the timer is complete. I'm not sure to why its doing that. Any help is appreciated
$(document).ready(function() {
$("#start_timer").click(
function () {
var totalTime = $("#time").val();
var interval = $("#interval").val();
var isValid = true;
$("#progressbar").progressbar({
value:0
});
// validate the time
if (totalTime == "") {
$("#time_error").text("This field is required.");
isValid = false;
} else if (isNaN(totalTime)) {
$("#time_error").text("Time must be a number.");
isValid = false;
} else {
$("#time_error").text("");
}
// validate the interval
if (interval == "") {
$("#interval_error").text("This field is required.");
isValid = false;
} else if (isNaN(interval)) {
$("#interval_error").text("Interval must be a number.");
isValid = false;
} else {
$("#interval_error").text("");
}
if (isValid) {
totalTime = totalTime * 1000;
interval = interval * 1000;
var elapsedTime = 0;
var displayMinutes = 0;
var displaySeconds = 0;
var timer = setInterval(
function () {
elapsedTime += interval;
displaySeconds = elapsedTime / 1000;
$("#progressbar").progressbar("value", elapsedTime);
/*if (displaySeconds < 60) {
$("#elapsed").val(displaySeconds + " seconds");
} else {
displayMinutes = parseInt(displaySeconds / 60);
displaySeconds = displaySeconds % 60;
if (displaySeconds == 0) {
$("#elapsed").val(displayMinutes + " minutes");
} else {
$("#elapsed").val(displayMinutes + " minutes " + displaySeconds + " seconds");
}
}
if (elapsedTime == totalTime) {
clearInterval(timer);
$("#complete span").text("Time is up!")
}*/
},
interval );
}
}
);
$("#totalTime").focus();
});

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