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);
};
Related
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;
I'm making a simple countdown timer, the user inters the day and month then the website shows how many days and hours remaining till the event.
my problem is that when the user sets a date but then he changes it to another my code displays both remaining days
html code :
<h1>Calander</h1>
<input id="inputday" type="text" placeholder="day">
<input id="inputMonth" type="text" placeholder="month">
<p id="output"></p>
JS code :
let inputM
let inputDay
const inputYear = 2022
let runOrNot = 0
let log = 0
document.getElementById('inputMonth').addEventListener('keyup', event => {
inputM = event.target.value
runOrNot++
console.log(runOrNot)
if (runOrNot > 2) {
clearInterval() //not working
run()
}
})
document.getElementById('inputday').addEventListener('keyup', e => {
inputDay = e.target.value
runOrNot++
console.log(runOrNot)
if (runOrNot > 3) {
clearInterval() //not working
run()
}
})
function run() {
//clearInterval() //doesnt work
console.log(inputM)
console.log(inputDay)
const countDownDate = new Date(`${inputM} ${inputDay}, ${inputYear}`).getTime();
// Update the count down every 1 second
const x = setInterval(function() {
// Get today's date and time
const now = new Date().getTime();
// Find the distance between now and the count down date
const distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
// Output the result
document.getElementById("output").innerHTML = days + "d " + hours + "h "
+ minutes + "m ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("output").innerHTML = "EXPIRED";
}
}, 1000);
}
clearInterval doesn't work without argument. You should add global variable for intervalId.
let inputM
let inputDay
const inputYear = 2022
let runOrNot = 0
let log = 0
document.getElementById('inputMonth').addEventListener('keyup', event => {
inputM = event.target.value
runOrNot++
console.log(runOrNot)
if (runOrNot > 2) {
clearInterval(intervalId) //not working
run()
}
})
document.getElementById('inputday').addEventListener('keyup', e => {
inputDay = e.target.value
runOrNot++
console.log(runOrNot)
if (runOrNot > 3) {
clearInterval(intervalId) //not working
run()
}
})
var intervalId;
function run() {
clearInterval(intervalId) //doesnt work
console.log(inputM)
console.log(inputDay)
const countDownDate = new Date(`${inputM} ${inputDay}, ${inputYear}`).getTime();
// Update the count down every 1 second
intervalId = setInterval(function() {
// Get today's date and time
const now = new Date().getTime();
// Find the distance between now and the count down date
const distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
// Output the result
document.getElementById("output").innerHTML = days + "d " + hours + "h "
+ minutes + "m ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(intervalId);
document.getElementById("output").innerHTML = "EXPIRED";
}
}, 1000);
}
<h1>Calander</h1>
<input id="inputday" type="text" placeholder="day">
<input id="inputMonth" type="text" placeholder="month">
<p id="output"></p>
clearInterval() expects an interval ID returned by setInterval:
clearInterval(intervalID)
intervalID
The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval().
It doesn't matter that your code is only using one interval - you have to pass the interval ID to clearInterval.
const interval_id = setInterval(function() {
console.log("Do something")
}, 1000)
// code ...
// stop the interval created earlier
clearInterval(interval_id)
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>
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 2 years ago.
So, I am a novice in Javascript and I am wondering if someone can help me with this. I believe this question is really really easy for most. Well, this is a countdown timer with select options to set up the time. It is working well. The problem is that, when the countdown starts, I want the single digit numbers to show the number zero first. Basically, I want the numbers for HH:MM:SS to be 2 digits. For example, 00:01:59 and not 0:1:59. I believe it has something to do with padString or something (I could be wrong), but my proficiency is still no that advanced.
Note: I would highly appreciate it if we can come up with a Vanilla Javascript solution and not JQuery simply because I want to use this offline and without any online dependencies. Thank you in advance.
Javascript
<script>
var hours = 0;
var minutes = 0;
var seconds = 0;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = displayHours + ":" +
displayMinutes + ":" + displaySeconds;
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
</script>
You could use ('0' + myValue).substr(-2) to fix the length with 2 characters. In this case '01' would be stay as '01' and '012' will be '12' because the -2 will cut the string from the end. Then your code will be:
var hours = 00;
var minutes = 00;
var seconds = 00;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = ('0' + displayHours).substr(-2) + ":" +
('0' + displayMinutes).substr(-2) + ":" + ('0' + displaySeconds).substr(-2);
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
I am struggling to make this code to work with localStorage so if anyone can help me that would be amazing. How do I implement a localStorage in order to save the countdown when refreshing the page?
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
return h + m;
}
var counter = setInterval(timer, 1000);
function timer() {
deadline--;
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}
Store the value in the localStorage everytime the value gets decreased.
When you reload the page, check if the stored time exists, if yes store it in your deadline variable, otherwise let the deadline be the initial one.
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
console.log(h)
console.log(m)
return h + m;
}
var counter;
var storedTime = localStorage.getItem('deadline')
if (storedTime) {
deadline = Number(storedTime)
}
counter = setInterval(timer, 1000);
function timer() {
--deadline;
localStorage.setItem('time', deadline);
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}