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

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>

Related

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;

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

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>

why my timer in POO doesn't work ? (javascript)

I created a timer in procedural which works ....
```let startMinutes = 1;
let time = startMinutes * 60;
let btnTimer = document.getElementById('btn-signer');
const countdownElt = document.getElementById('countdown');
let interval = setInterval(updateCountDown, 1000);
function startTimer() {
interval = setInterval(updateCountDown, 1000);
}
btnTimer.addEventListener("click", function () {
startTimer()
});
function updateCountDown() {
const minutes = Math.floor(time / 60); //nombre entier
let seconds = time % 60; //reste division
seconds = seconds < 10 ? '0' + seconds : seconds;
countdownElt.innerHTML = `Temps restant : ${minutes}min ${seconds}sec`;
time--;
if (minutes <= 0 && seconds <= 0) {
clearInterval(interval);
countdownElt.innerHTML = "Temps écoulé, veuillez réserver à nouveau.";```
I have to transform it in POO but it doesn't works, I thank that maybe I need to create parameters in consctructor but I don't know if it's really necessary and I don't know which parameters to use..
``` class countDown {
constructor() {
this.btnTimer = document.getElementById('btn-signer');
this.countdownElt = document.getElementById('countdown');
this.startMinutes = 1;
this.timeSec = this.startMinutes * 60;
this.interval = setInterval(this.updateCountDown, 1000);
this.btnTimer.addEventListener('click', () => this.startTimer());
this.updateCountDown();
}
startTimer() {
this.interval = setInterval(this.updateCountDown, 1000);
//console.log(this.interval);
}
updateCountDown() {
let minutes = Math.floor(this.timeSec / 60); //nombre entier
let seconds = this.timeSec % 60; //reste division
seconds = seconds < 10 ? '0' + seconds : seconds;
document.getElementById('countdown').innerHTML = `Temps restant : ${minutes}min ${seconds}sec`;
this.timeSec--;
if (minutes <= 0 && seconds <= 0) {
clearInterval(this.interval);
this.countdownElt.innerHTML = "Temps écoulé, veuillez réserver à nouveau.";
}
}
}```
Thanks.

Add milliseconds to JavaScript

I created a simple game for which I need a countdown. Now everything is fine, but I need to add a millisecond to the timer. I used the code found on the internet, but it lacks just those milliseconds. My attempts have not been successful, so I am asking you for help.
var seconds;
var temp;
function countdown() {
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
if (seconds == '') {
temp = document.getElementById('countdown');
temp.innerHTML = '00:00:00';
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = secondsToTime(seconds);
timeoutMyOswego = setTimeout(countdown, 1000);
}
function timeToSeconds(timeArray) {
var minutes = (timeArray[0] * 1);
var seconds = (minutes * 60) + (timeArray[1] * 1);
return seconds;
}
function secondsToTime(secs) {
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
minutes = minutes < 10 ? '0' + minutes : minutes;
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = seconds < 10 ? '0' + seconds : seconds;
return minutes + ':' + seconds;
}
countdown();

How can I make a timer subtract five minutes when a buton is pressed?

I'm making a riddle where people have 45 minutes to find the solution, but I want the timer to go down five minutes when they answer incorrectly to prevent them from just guessing the answer. This is what I have for the timer:
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
var cat1 = $("input[#name=Verdachte]:checked");
if (cat1.val() != "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
But it just keeps subtracting five minutes all the time, so I made a send button for it:
$("#results").click(function() {
if (cat1.val() === "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
};
But now the timer just disappears completely, how can I fix this?
try this , I create a new function to check value and set varaibles as globals to access easy ,and change value of 'start' if value of textbox is wrong
var start = Date.now();
function startTimer(duration, display) {
var diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
function checkValue() {
var cat1 = $("#Verdachte");
if (cat1.val() == "2" || cat1.attr("disabled")) {
cat1.val("you are right :)");
cat1.attr("disabled", true);
} else {
cat1.val("Wrong :(");
start -= 1000 * 60 * 5;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
<input id="Verdachte">
<button onclick="checkValue()"> click me</button>

Categories

Resources