How would I use clearInterval() here to stop timer when reaches 0? - javascript

Here is a simple timer, how would I implement clearInterval() in this bit of code when the timer reaches 0? It currently is infinite.
const start = 0.1; //6 seconds
let time = start * 60;
const count = document.querySelector('#countdown-timer');
const interval = setInterval(updateTimer, 1000);
function updateTimer() {
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
count.innerHTML = `${minutes}:${seconds}`;
time--;
}
<span id="countdown-timer"></span>

Like this
Also you can simplify the padding
const start = 0.1; //6 seconds
let time = start * 60;
const count = document.querySelector('#countdown-timer');
const interval = setInterval(updateTimer, 1000);
function updateTimer() {
if (time<=0) clearInterval(interval)
const minutes = Math.floor(time / 60);
let seconds = time % 60;
count.innerHTML = `${minutes}:${String(seconds).padStart(2,'0')}`;
time--;
}
<span id="countdown-timer"></span>

Related

React Native Interval Counter problems

hello i am writing a coutndown app that should count down from seconds as soon as you press the button it will then determine if the seconds also contain hours minutes and days and then as countdown format 00:00: 00 the problem is that my countdown doesn't want to work properly because it somehow gets confused when counting down and sometimes counts down the wrong countdown when i start it again i want the countdown to start again by itself or can be stopped by a top button and that the countdown counts down correctly does anyone know how to fix this error i don't understand why this doesn't work
var seconds = state.count;
const btnStartCountdown = () => {
clearInterval(intervalId);
setIntervalId(0);
}
const btnStopCountdown = () => {
clearInterval(intervalId);
}
const newIntervalId = setInterval(() => {
let days = Math.floor(seconds / 24 / 60 / 60);
let hoursLeft = Math.floor(seconds - days * 86400);
let hours = Math.floor(hoursLeft / 3600);
let minutesLeft = Math.floor(hoursLeft - hours * 3600);
let minutes = Math.floor(minutesLeft / 60);
let remainingSeconds = seconds % 60;
// let percent = (remainingSeconds * 1000) / 100;
//console.log(percent);
//setProgress(percent);
const pad = n => {
return n < 10 ? '0' + n : n;
};
setTime(`${pad(hours)}:${pad(minutes)}:${pad(remainingSeconds)}`); // update the new countdown value
if (seconds == 0) {
clearInterval(intervalId);
setIntervalId(0);
return;
} else {
seconds--;
}
}, 1000);
setIntervalId(newIntervalId);
clearInterval(intervalId);
};

Javascript Continue From a Specific Time

I have a timer and a time. The time format is like the currentTime variable in my code. I want to get the currentTime time and add +1 to it every second keeping the same time format. Also I would like to subtract the currentTime + 1 - the total hours but keeping it real time with setInterval. Hope I am clear about my questions. Thanks.
HTML
<button id="start">START</button>
<button id="pause">PAUSE</button>
<div id="output"></div>
Javscript
const startTimeButton = document.querySelector("#start")
const pauseTimeButton = document.querySelector("#pause")
const output = document.querySelector("#output");
let currentTime = "12: 42: 17";
let totalHours = 30;
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
return `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "flex";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "flex";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
// Here is an example of what I would like to achive
// currentTime + 1 (each second)
// output.innerHTML = (parseInt(currentTime) + 1) - totalHours;

Alarm when time reaches zero

The problem I have here is when I try to implement the audio is that it keeps on playing every second, I have included the source for the audio code at the very bottom if you may need it.
let time = startingMinutes * 60;
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--;
time = time < 0 ? 0 : time;
}
const audio = new Audio();
audio.src = "alarm.mp3"; ```
You need to clear setInterval once timer reaches 0 and also need to put the audio code inside updateCountdown function when timer reaches 0. Additionally you can use a global variable to track if audio is played or not and use it conditionally. Check the code.
document.addEventListener('DOMContentLoaded', function() {
let startingMinutes = 1; // one min
let time = startingMinutes * 60;
var audioPlayed = false; // audio is not played - create a global variable to track if audio is already played (optional)
const countdownEl = document.getElementById('Countdown');
const counterInterval = 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--;
time = time < 0 ? 0 : time;
if(!time && !audioPlayed) {
const statusEl = document.getElementById('Status');
var status = "timer reaches 0";
// prefered - clear interval, so once timer reaches zero, there will be no more call to updateCountdown
clearInterval(counterInterval);
status += ", clear setInterval";
// this is optional, in case the code above not work for any reason
// set the global var audioPlayed to true to indicate audio is played
audioPlayed = true;
status += ", audio play starts";
Status.innerHTML = status;
// run your audio
// const audio = new Audio();
// audio.src = "alarm.mp3";
}
}
});
<html>
<span id="Countdown"></span> <span id="Status"></span>
</html>
For the people viewing this question and would like an answer. Please note this audio will keep on playing as the timer stays at 0
const startingMinutes= 1;
let time = startingMinutes * 60;
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--;
time = time < 0 ? 0 : time;
if (time <=0) {audio.play()};
}
const audio = new Audio();
audio.src = "alarm.mp3";

Javascript Counter Troubleshooting

Working on making a 2 minute timer in JS.
I'm new so please bear with me.
I want to make the timer so that when you click the button (I already made the button in js), it decrements the time from 2 minutes. Here is what I have so far. The code doesn't go down second by second. Any suggestions would be helpful, thank you!
const startingMinutes = 2
let time = startingMinutes * 60
let timerId = setInterval(countDown, 1000)
function countDown() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
time--
if (timerId <= -startingMinutes) {
countdown.innerHTMl = 'Good Luck!'
clearInterval(timerId)
}
if (timerId <= 0) {
countdown.innerHTML = 'Time is up!'
clearInterval(timerId)
}
button.addEventListener('click', () => {
countDown()
countdown.innerHTML = minutes + ' minutes ' + ': ' + seconds + ' seconds '
})
}
timerId = setInterval(countDown, 1000)
This work successfully:
const startingMinutes = 0.25
let time = startingMinutes * 60
let timerId = setInterval(countDown, 1000)
function countDown() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
time--
console.log(minutes, 'minutes:', seconds, 'seconds');
if (time <= 0) {
console.log('Time is up!');
clearInterval(timerId)
}
}
Then, just call setInterval with countDown function in your click handler

How do I automatically restart the countdown timer after it reaches 0?

I am trying to find a way to restart my countdown timer at 2:00 again when it reaches 0:00. I don't know if I'm wrong, but it won't work.
const startingMinutes = 2;
let time = startingMinutes * 60;
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--;
time = time < 0 ? 0 : time;
if (time == 0) {
fn();
setInterval(updateCountdown, 1000)
return;
}
}
<p id="countdown">2:00</p>
Reset the time once it hits zero, and you don't need to call setInterval again. Also, by calling updateCountdown() directly we can avoid hardcoding 2:00 in the HTML.
const startingMinutes = 2;
let time = startingMinutes * 60;
const countdownEl = document.getElementById('countdown');
function updateCountdown(){
const minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
countdownEl.innerHTML = `${minutes}:${seconds}`;
time--;
time = time < 0 ? 0 : time;
if (time == 0) {
// fn(); <-- not sure what this is supposed to do, so I commented it out
time = startingMinutes * 60; // reset counter
}
}
setInterval(updateCountdown, 1000);
updateCountdown();
<p id="countdown"></p>
Just reset your time:
Sample
var startingMinutes = 2;
let time = startingMinutes * 60;
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--;
time = time < 0 ? 0 : time;
if (time == 0) {
fn();
time = startingMinutes * 60;
return;
}
function fn() {
console.log("timer reset");
}
}
<p id="countdown">2:00</p>
Slightly different methodology.
window.addEventListener('load', ticker(120, countdown('countdown')))
function countdown(target) {
let counter = document.getElementById(target)
return (now) => {
let minutes = Math.floor(now / 60)
let seconds = Math.round((now / 60) % 1 * 60)
seconds = seconds >= 0 && seconds < 10 ? seconds = '0'+seconds : seconds
counter.textContent = minutes+':'+seconds
}
}
function ticker(seconds, tick, step = 1000) {
let now = seconds;
(function next() {
tick(now)
now = now - 1 || seconds
setTimeout(next, step)
})()
}
<p id="countdown">Loading...</p>

Categories

Resources