I can't get this countdown timer button working - javascript

I have a countdown timer I am working on but cant get it to work. I don't really understand how I got this far with it as I am not a developer. The function is: You input a timer like 1 minute, and the countdown timer counts down and reaches zero. It then pays a sound and starts the countdown again.
After you press the Start Timer button, the countdowns being. And the button changes to STOP. So you can stop the timer at any point, then when you stop the timer the button changes to START/RESUME so you can start the timer again.
The problem is that the timer STOP button only works the first time counting down. After that it doesn't work. Any ideas from the pros, how I can fix this?
const timerDisplay = document.getElementById("timerDisplay");
const startButton = document.getElementById("startButton");
const timeInput = document.getElementById("timeInput");
const audio = new Audio('alarm.mp3');
let interval;
let start;
let duration;
let elapsed;
let isRunning = false;
startButton.addEventListener("click", function() {
if (!isRunning) {
duration = timeInput.value * 60 * 1000;
startTimer(duration);
startButton.innerHTML = "Stop";
isRunning = true;
} else {
clearInterval(interval);
startButton.innerHTML = "Resume";
isRunning = false;
}
});
function startTimer(duration) {
start = Date.now();
let timer = duration,
minutes, seconds;
interval = setInterval(function() {
elapsed = Date.now() - start;
timer = duration - elapsed;
minutes = parseInt(timer / 60000, 10);
seconds = parseInt((timer % 60000) / 1000, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
timerDisplay.innerHTML = minutes + ":" + seconds;
if (timer < 0) {
clearInterval(interval);
timerDisplay.innerHTML = "Change Exercises!";
audio.play();
start = Date.now();
timer = duration;
}
}, 1000);
audio.addEventListener("ended", function() {
startTimer(duration);
startButton.innerHTML = "Stop";
isRunning = false;
});
}
<p>
<label for="timeInput">Set Time:</label>
<input type="number" id="timeInput" value="1">
</p>
<p>
<button id="startButton">Start Timer</button>
</p>
<p id="timerDisplay"></p>
This actualy doesnt restart when the countdown reaches zero. But it still restarts on my server? Not sure whats thats about.

Related

How to get a timer to end on 0:00 in javascript

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>

Adding time on button click to a count down timer

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>

How to change timer into a countdown timer for the Memory game

I have a code for a Memory game with images. I took the reference for the game from this link:
Memory game
In this code , the game has a clock/ timer. I would like to make this timer into a clock down timer setting a limit of 10 mins. I dont know how to change this timer into clock down time. Can someone help me out with this problem.
// #description game timer
var second = 0,
minute = 20;
hour = 0;
var timer = document.querySelector(".timer");
var interval;
function startTimer() {
interval = setInterval(function() {
timer.innerHTML = minute + "mins " + second + "secs";
second++;
if (second == 60) {
minute++;
second = 0;
}
if (minute == 60) {
hour++;
minute = 0;
}
}, 1000);
}
//reset timer
second = 0;
minute = 20;
hour = 0;
var timer = document.querySelector(".timer");
timer.innerHTML = "20 mins 0 secs";
clearInterval(interval);
startTimer();
<div class="timer">
</div>
Can someone show me how to change this normal timer into a countdown timer and help me out of this problem.
Try this one.
var second = 0,
minute = 20;
hour = 0;
var timer = document.querySelector(".timer");
var interval;
function startTimer() {
interval = setInterval(function() {
timer.innerHTML = hour + " hr " + minute + " mins " + second + " secs";
if (second == 0) {
if (minute == 0) {
hour--;
minute = 60
}
minute--;
second = 60
}
second--;
}, 1000);
}
//reset timer
second = 0;
minute = 20;
hour = 0;
var timer = document.querySelector(".timer");
timer.innerHTML = "0 hr 20 mins 0 secs";
clearInterval(interval);
startTimer()
<html>
<body>
<div class="timer"></div>
</body>
</html>

timer pop up wont stop looping when time is up

trying to create a timer that starts when button is clicked and send a pop up when time is up on my game
I have tried breaking the loop but when this happens pop up no longer appears
document.getElementById('start').addEventListener('click', function (){
var oneMinute = 60,
display = document.querySelector('.timer');
startTimer(oneMinute, display);
render();
});
function startTimer(duration, display){
var timer = duration, minutes, seconds;
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;
document.querySelector('button').addEventListener('click', function(){
render();
})
if (--timer <= 0) {
timer = "0.00";
clearInterval(timer);
swal.fire(`YOU FAILED FINAL SCORE ${points}`)
}
}, 1000)
};
render();```
Your issue is here var timer = duration and here clearInterval(timer).
duration is a parameter and not an interval ID which clearInterval requires that's set by setInterval.
So really you want to reference the interval and clear by the same reference.
var interval = setInterval(function (){
...
}, 1000);
Replace your clearInterval(timer); with clearInterval(interval);

How can I make this JavaScript Timer function properly?

I am trying to make a timer using JavaScript. The problem is, I can't get the timer to stop when it reaches 0. I have tried using return and if statements, but nothing seems to be working. Am I on the right track, or is there a better way to do this?
<input type="text" id="minutes" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<span>:</span>
<input type="text" id="seconds" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<button onclick="timer()">Set</button>
<script>
//This prototype correctly uses the modulus function when dealing with negative numbers.
Number.prototype.mod = function (m) {
return ((this % m) + m) % m
}
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
var initial = seconds * 1000 //Amount of seconds (converted to milliseconds) initially set.
var milliseconds = (minutes * 60000) + (seconds * 1000) //Total amount of milliseconds set.
setTimeout(function () {
alert("Time's up!")
}, milliseconds) //Display a message when the set time is up.
/*\Decreases the minute by one after the initially set amount of seconds have passed.
|*|Then, clears the interval and sets a new one to decrease the minute every 60 seconds.
\*/
test = setInterval(function () {
minutes--;
document.getElementById('minutes').value = minutes;
clearInterval(test)
setInterval(function () {
minutes--;
document.getElementById('minutes').value = minutes
}, 60000)
}, initial)
//Seconds are set to decrease by one every 1000 milliseconds, then be displayed in the seconds box.
setInterval(function () {
seconds--;
document.getElementById('seconds').value = seconds.mod(60)
}, 1000)
}
You have four different timer functions (setTimer and two setIntervals) when you only need one. JSFiddle
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
var intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
}
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
if (minutes == 0 && seconds == 0) {
alert("Time's up!");
clearInterval(intervalTimer);
}
}, 1000);
}
In general, you need to make sure every setInterval is given a name (var x = setInterval...) and cleared later on (clearInterval(x)). You could have separate timers (one for the minutes which starts after the given number of seconds then repeats every 60 seconds, one for seconds, and one to display the message) if you really want to for some reason, as long as you clear all of the interval timers once the countdown reaches zero.
Using two timers might make sense, however. This would make sure that the Time's up message really appears when it's supposed to, even if there is any imprecision in the interval timer.
function timer() {
var minutes = document.getElementById('minutes').value,
seconds = document.getElementById('seconds').value,
intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
}
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
}, 1000);
setTimer(function () {
alert("Time's up!");
clearInterval(intervalTimer);
}, minutes * 60000 + seconds * 1000);
}
I made improvements to Stuart's answer: fiddle
Basically the same thing, except it works properly:
function clearTimer() {
clearInterval(intervalTimer);
}
var intervalTimer;
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds += 60;
minutes--;
}
if (minutes < 0) {
alert("Time's up!");
clearTimer();
} else {
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
}
}, 1000);
}
Im not a great javascript guy, but maybe this will help. i made this in typescript http://www.typescriptlang.org/Playground/
but i would do timing different and use the javascript date object and calculate differences. This is a simple example of how i would start to create a time (without the date object)
javascript
var Timer = (function () {
function Timer(time) {
this.accuracy = 1000;
this.time = time;
}
Timer.prototype.run = function (button) {
var _this = this;
this.time -= 1; //this is inaccurate, for accurate time use the date objects and calculate the difference.
//http://www.w3schools.com/js/js_obj_date.asp
button.textContent = this.time.toString();
if (this.time > 0) {
setTimeout(function () {
return _this.run(button);
}, 1000);
}
};
return Timer;
})();
var time = new Timer(10);
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);
typescript(in case you wonder)
class Timer {
accuracy = 1000;//update every second
time: number;
constructor(time: number) {
this.time = time;
}
run(button: HTMLButtonElement) {
this.time -=1;//this is inaccurate, for accurate time use the date objects and calculate the difference.
//http://www.w3schools.com/js/js_obj_date.asp
button.textContent = this.time.toString();
if(this.time > 0)
{
setTimeout(()=> this.run(button),1000);
}
}
}
var time = new Timer(10)
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);

Categories