Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
Now I have got the first 2 step to work with my current code, but I'm having a lot of issues with the 3rd part. Once the user clicks the add 1.45 button the count works, but only up until a certain point. After this point it will start to display a negative integer.
I'm sure there is an easier way to write this code. I have really overcomplicated this. Any suggestions would be appreciated.
//Define vars to hold time values
let startingMins = 3.5;
let time = startingMins * 60;
//define var to hold stopwatch status
let status = "stopped";
//define var to holds current timer
let storeTime = null;
//define Number of sets
let setNum = 1;
//Stop watch function (logic to determin when to decrement each value)
function stopwatch () {
minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
storeTimer = minutes + ":" + seconds; //Store time in var
storeTime = minutes + "." + seconds; //Store time in var
//Display updated time values to user
document.getElementById("display").innerHTML = storeTimer;
time--;
// When timer reachers 0 secs the inital 3:30 countdown will begin again.
if (time <= 0) {
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
setNum++;
//console.log(setNum);
}
}
function StartStop() {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 100);
var startButton = document.getElementById("start");
document.getElementById("start").innerHTML = "Pauce";
//startButton.style.display = "none"
status = "start";
//console.log(time);
}
else {
window.clearInterval(interval);
document.getElementById("start").innerHTML = "Start";
status = "stopped";
console.log(storeTime);
}
}
function pauceAdd () {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 1000);
var zukButton = document.getElementById("pauceAdd");
status = "start";
}
else {
window.clearInterval(interval);
status = "stopped";
console.log("store time " + storeTime);
let time = +storeTime + +1.45; //store time is 3.30 adding 4.75
console.log("store time2 " + time); // correct result 4.75
minutes = Math.floor(time);/// convert time from Mins (4.75) to seconds (475)
let seconds = time % 60; // 5
if (seconds < 60 ) { // if the Stored time is greater than 60 secs add 1 minute to the timer
minutes++;
seconds = seconds * 100;
console.log("secs updated = " + seconds ); // seconds updated (475)
if (seconds <= 460) {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 == " + seconds)
}
else if (seconds > -60) { // Stuck here
seconds = seconds + 60;// Stuck here
}// Stuck here
else {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 = " + seconds)
}
}
if (seconds < 1) {
seconds = seconds + 60;
minutes = minutes - 1;
}
seconds = seconds < 10 ? + seconds : seconds;
console.log("mins updated = " + minutes + "__________________________-");
//Display updated time values to user
document.getElementById("display").innerHTML = minutes + ":" + seconds;
}
}
function reset () {
//window.clearInterval(storeTime);
window.clearInterval(interval);
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
status = "stopped";
setNum = 1;
var startButton = document.getElementById("start");
startButton.style.display = "inline-block";
document.getElementById("display").innerHTML = "3:30";
document.getElementById("start").innerHTML = "Start";
}
I might have taken the requirements a bit too literally:
Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the
timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
There's a trick to countdown timers. You have to use timestamps to find out how much time ACTUALLY elapsed. You can't trust that your interval will fire exactly every second. In fact, it almost always fires a bit later (in my tests, about 2-3 milliseconds, but I was logging to the console as well, so that might have skewed the test).
let interval, timestamp;
let countdown = 210000;
document.addEventListener("DOMContentLoaded", () => {
document
.querySelector("button")
.addEventListener("click", (event) => toggleState(event.target));
});
function toggleState({ dataset }) {
timestamp = Date.now();
if (dataset.state == "running") {
clearInterval(interval);
countdown += 105000;
updateDisplay(dataset, "paused");
} else {
interval = setInterval(() => updateCountdown(dataset), 100);
updateDisplay(dataset, "running");
}
}
function updateCountdown(dataset) {
const now = Date.now();
countdown -= now - timestamp;
if (countdown <= 0) countdown = 210000;
timestamp = now;
updateDisplay(dataset, "running");
}
function updateDisplay(dataset, label) {
dataset.state = label;
dataset.time = `(${new Date(countdown).toISOString().slice(14, 19)})`;
}
button::before {
content: attr(data-state);
}
button::after {
content: attr(data-time);
padding-left: 0.5em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<button data-state="stopped" data-time="(03:30)"></button>
Related
I have a timer that counts down from an amount of minutes which a user puts in but now I don't know how to get it to stop once the timer runs out
This is my javascript coding:
function getTime(){
const startingMinutes=prompt("How many minutes is your timer?");
let time=startingMinutes*60;
var overMin=0;
var overSec=00;
const countdownEl=document.getElementById("countdown");
setInterval(updateCountdown, 1000);
function updateCountdown(){
const minutes=Math.floor(time/60);
let seconds= time % 60;
seconds=seconds<10 ? '0' + seconds : seconds;
countdownEl.innerHTML= `${minutes}:${seconds}`;
time--;
if (minutes==0 && seconds==00){
document.getElementById('timesUp').play();
return;
}
}
}
What this ended up doing was playing the timer sound then the timer went backwards when I was trying to get it to stop.
setInterval() returns a timer ID. Use that to cancel it later with clearTimeout():
function getTime() {
const startingMinutes = prompt("How many minutes is your timer?");
let time = Number(startingMinutes) * 60 + 1;
const countdownEl = document.getElementById("countdown");
const timerId = setInterval(updateCountdown, 1000);
function updateCountdown() {
time--;
const minutes = Math.floor(time / 60);
let seconds = time % 60;
countdownEl.innerHTML = minutes + ':' + ('0' + seconds).slice(-2);
if(time <= 0) {
document.getElementById('timesUp').innerHTML = 'Done!';
clearTimeout(timerId);
}
}
}
getTime();
Count down: <span id="countdown"></span>
<div id="timesUp"></div>
There is a counter that counts down from 25. When I click on the link of the page, it continues to count from wherever it is left. So when I start at 25 and exit the page, it shows 15 when I come back 10 seconds later. But when I open it with a different browser, there is a different number, so the counter does not always show the same value. What could be the reason for this and what can I do?
var interval = 25000;
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("timer").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);
I have a timer which I am testing, it seems there is a bit of drift between when the minute countdown goes down by 1 and seconds whenever it reaches 59 seconds ()ie every minute:-
How can I alter this so they are both in sync?
my code is the following:-
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - ((now() - initTick) / 1000);
timeRemaining = timeRemaining >= 0 ? timeRemaining : 0;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining.toFixed() % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
if (timeRemaining > 0) {
setTimeout(tick, delay);
}
}
var countdown = 600; // time in seconds until user may login again
var delay = 20; // time (in ms) per tick
var initTick = now(); // timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer"); // element to have countdown written to
setTimeout(tick, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle: https://jsfiddle.net/robbiemcmullen/cer8qemt/1/
The issue is the precision is not the same for minutes and seconds.
You need to round to the nearest second before /60 / %60.
Consider: exactly 9 mins remaining:
var x = 540;
console.log(x.toFixed() % 60, Math.floor(x / 60));`
Output is: (0,9)
Then consider the call 20 ms later:
var x = 539.980;
console.log(x.toFixed() % 60, Math.floor(x / 60));
the output is now: (0, 8).
So the seconds haven't changed (yet) but the minute does.
Here is a version using setInterval and removing the use of .toFixed ()
Why do you use an interval of 20ms and not 1 second?
//method for countdown timer
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - elapsedTime;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
++elapsedTime;
return timeRemaining;
}
var countdown = 600;
var elapsedTime = 0;
var timeRemaining;
// countdown: time in seconds until user may login again
//var delay = 20;
// delay: time (in ms) per tick
var initTick = now(); // initTick: timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer");
// countdownTimer: element to have countdown written to
var interval = setInterval(function() {
if(tick() <= 0) {
clearInterval(interval);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle https://jsfiddle.net/ud3wm8t1/
// This timer keeps reseting back to 2:00 after it reaches 1 minute. Also i do not get a notification that says times up at the right time. Can someone please correct the code. Also the stop/resume timer button also has to stay functional.
var isRunning = false;
var ticker; //this will hold our setTimeout
var seconds,
minutes;
function countdown(mins, secs) {
//i made these global, so we can restart the timer later
seconds = secs || 60; //if user put in a number of minutes, use that. Otherwise, use 60
minutes = mins;
console.log('time stuff',mins,secs,minutes,seconds)
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds < 1 && minutes) {
//seconds reached 0, and still minutes left;
seconds=60;
minutes--;
}
if ((seconds > 0 || minutes > 0) && isRunning) {
ticker = setTimeout(tick, 1000);
} else if(isRunning){
console.log(seconds,minutes,isRunning)
alert('Time\'s up, brah!')
}
}
tick();
}
function timeToggle() {
isRunning = !isRunning; //if it's false, set it true. If it's true, set it false.
if (!isRunning) {
clearTimeout(ticker); //or whatever else you set the initial timeOut to.
} else {
//not running! and time is defined;
var sec = seconds||60;
console.log('def!',minutes, sec)
countdown(minutes, sec);
}
}
isRunning = true;
countdown(2);
<div id="timer">2:00</div>
<button onclick="timeToggle()">Stop time</button>
There is a small flaw in your logic.
During the countdown initialization your doing
seconds = secs || 60;
Which effectively add 60 seconds to the time you want if you don't initialize the seconds. see:
function countdownInit(mins, secs) {
seconds = secs || 60;
minutes = mins;
console.log(mins + 'min ' + seconds + 'sec');
}
countdownInit(1, 30) // ok
// 1min 30sec
countdownInit(1) // not ok
// 1min 60sec
// thats 2 minutes
The second issue here is that you use a var current_minutes that equals minutes - 1 to display the time. So you are not showing the real counter.
the fix is as follow:
function countdown(mins, secs) {
seconds = secs;
minutes = mins;
// if secs is 0 or uninitialized we set seconds to 60 and decrement the minutes
if(!secs) {
minutes--;
seconds = 60;
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
// we use minutes instead of current_minutes in order to show what's really in our variables
counter.innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// rest of code
}
// rest of code
}
I tried to keep as much as your code as possible.
I'm creating a countdown timer based on a users input. When the user pauses and resumes, the timer restarts at the initial inputed value and fails to resume from the current interval. I've uploaded the code into Codepen.
http://codepen.io/alivera/pen/JGpvRx
//Timer
var myTimer;
var duration = sessionCounter * 60;
var startTimer = function() {
minutes = parseInt(duration / 60);
seconds = parseInt(duration % 60);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
document.getElementById("clockTimer").innerHTML = minutes + ":" + seconds;
if (--duration < 0) {
document.getElementById("toggleStatus").innerHTML = "<br>Break!";
}
};
//Start Timer
var go = function() {
myTimer = setInterval(startTimer, 1000);
document.getElementById('start').innerHTML = "Stop";
document.getElementById('start').className = "btn btn-danger";
document.getElementById("start").onclick = stop;
};
//Stop Timer
var stop = function() {
clearInterval(myTimer);
document.getElementById('start').innerHTML = "Start";
document.getElementById('start').className = "btn btn-success";
document.getElementById("start").onclick = go;
};
duration.onload = stop();
You're loading the time to count down from from the #clockTimer element:
var sessionCounter = document.getElementById("clockTimer").innerHTML;
This is bad because the contents of that element are changing. Often.
And parseInt on the next line only is only giving you the number before the colon. Your best bet for solving this problem would be storing the current time remaining and the previously set time in separate variables, as I have done below.
Your code was a little difficult to work with, so while correcting the error(s), I ended up almost completely rewriting it.
Here's my version; I'll explain it line-by-line (or section-by-section, or whatever):
First, put all of our elements in to easy-to-use (and type) variables:
var subBreakButton = document.getElementById("subBreakButton"),
breakTimer = document.getElementById("breakTimer"),
addBreakButton = document.getElementById("addBreakButton"),
subSessionButton = document.getElementById("subSessionButton"),
sessionTimer = document.getElementById("sessionTimer"),
addSessionButton = document.getElementById("addSessionButton"),
breakSession = document.getElementById("breakSession"),
clockTimer = document.getElementById("clockTimer"),
These variables are in seconds (thus m * s):
breakLength = 5 * 60, // Minutes to seconds
sessionLength = 25 * 60, // Minutes to seconds
sessionTimeLeft = sessionLength;
Next, a helper method that formats times into a mm:ss ... format:
function timeString (seconds) {
var minutes = parseInt(seconds / 60) + "",
seconds = parseInt(seconds % 60) + "";
if (minutes.length === 1)
minutes = "0" + minutes;
if (seconds.length === 1)
seconds = "0" + seconds;
return minutes + ":" + seconds;
}
Third, event listeners for the plus and minus buttons:
// Event Listeners
addBreakButton.addEventListener("click", function () {
breakLength += 1 * 60;
breakTimer.innerHTML = timeString(breakLength);
});
subBreakButton.addEventListener("click", function () {
breakLength -= 1 * 60;
if (breakLength < 0)
breakLength = 0;
breakTimer.innerHTML = timeString(breakLength);
});
addSessionButton.addEventListener("click", function () {
sessionLength += 1 * 60;
sessionTimer.innerHTML = timeString(sessionLength);
});
subSessionButton.addEventListener("click", function () {
sessionLength -= 1 * 60;
if (sessionLength < 0)
sessionLength = 0;
sessionTimer.innerHTML = timeString(sessionLength);
});
And, the fun part:
// Timer
var myTimer;
function startTimer () {
if (myTimer) // Check to see if a timer was already running, and if so, stop it
stopTimer();
sessionTimeLeft = sessionLength;
myTimer = setInterval(function () {
sessionTimeLeft--;
if (sessionTimeLeft <= 0) {
sessionTimeLeft = 0;
stopTimer();
}
clockTimer.innerHTML = (sessionTimeLeft <= 0? "Break!": timeString(sessionTimeLeft));
}, 1000);
}
function stopTimer () {
clearInterval(myTimer);
myTimer = 0;
}
Lastly, wrappers:
// Start Timer
function go() {
startTimer();
}
//Pause Timer
function stop() {
stopTimer();
}
Codepen: http://codepen.io/anon/pen/ZQjLZE?editors=1010