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
Related
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>
I have a simple question. I want to make this code work with the Reset time button when the time is start again from 30 min delete the ( You are Ready! ) and start the time
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
<span id="countdown" class="timer">
Reset time
I created a new function to reset the seconds and restart the timer and linked it to the button. I have also isolated at the start of the js code the variables that will count the seconds and hold the reference to the Interval.
is this what you are looking for?
var seconds;
var countdownTimer;
function startTimer() {
if (!seconds || seconds == 0) {
seconds = 30;
clearInterval(countdownTimer);
countdownTimer = setInterval(secondPassed, 1000)
secondPassed();
}
}
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "You are Ready!";
} else {
seconds--;
}
}
startTimer();
<html>
<body>
<div>
<span id="countdown" class="timer"></span>
</div>
Reset time
</body>
</html>
Here create a separate function where after clicking - it disables the button, sets the timer, and changes button text.
In secondPassed method, if seconds == 0, it enables the button, so that you can start count down again.
var seconds = 30;
var countdownTimer;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0)
{
clearInterval(countdownTimer);
document.getElementById('reset').disabled = false;
document.getElementById('countdown').innerHTML = "You are Ready!";
} else
{
seconds--;
}
}
function start(){
seconds = 30;
document.getElementById('reset').innerHTML = "Reset";
document.getElementById('reset').disabled = true;
countdownTimer = setInterval('secondPassed()', 1000);
}
//on load call
start();
<div>
<span id="countdown" class="timer"/>
</div>
<button id="reset" onclick="start()">
Start
</button>
Let's assume something quite basic, like the following:
<div>00:00</div>
<button>Reset</button>
Below is an approach you could take, fully-commented.
// We'll start by getting a couple element references
const label = document.querySelector("div");
const button = document.querySelector("button");
// Next, we'll bind-up the click handler for the button
button.addEventListener("click", () => {
// When the user clicks the button, we'll set the time
// limit to 30 minutes and proceed
let timer = 60 * 30;
// Disable the button to prevent further clicks
button.disabled = true;
button.dataset.default = button.textContent;
button.textContent = "Now counting down!";
// Let's setup some code that will be executed every second
button.interval = setInterval(() => {
// This decimal will be a number like 29.9521
const decimal = timer / 60;
// We'll convert 29.9521 into 29, for 29 minutes
const wholeMinute = Math.floor(decimal);
// Next, we'll take the .9521 and multiply by 60 for seconds
const wholeSecond = Math.round(60 * (decimal - wholeMinute));
// We'll pad both of the numbers so they always have a leading 0
const lblMin = wholeMinute.toString().padStart(2, 0);
const lblSec = wholeSecond.toString().padStart(2, 0);
// As long as we aren't out of seconds
if (timer >= 0) {
// Reduce the timer by 1 second
timer = timer - 1;
// And print the new label on our label element
label.textContent = `${ lblMin }:${ lblSec }`;
// Then return, so we don't execute what comes next
return;
}
// If we made it this far, our timer ran out
// Start by enabling the button
button.disabled = false;
// Restore the original text of the button
button.textContent = button.dataset.default;
// And clear our interval, as it is no longer needed
clearInterval(button.interval);
// Our interval will 'tick' once every second (1000 milliseconds)
}, 1000);
});
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>
i want this my javascript code to to be able to be reading 3 hours countdown and also redirect to a new page after the countdown is complete
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
please help me make it better by making it been able to countdown to three hour and also redirect to another page after the countdown is complete
You didn't properly set total time. You set it to 16 minutes instead of 3 hours. Here is the working code (try it on JSFiddle):
var time = 60 * 60 * 3;
var div = document.getElementById("timer");
var t = Date.now();
var loop = function(){
var dt = (Date.now() - t) * 1e-3;
if(dt > time){
doWhateverHere();
}else{
dt = time - dt;
div.innerHTML = `Hours: ${dt / 3600 | 0}, Minutes: ${dt / 60 % 60 | 0}, Seconds: ${dt % 60 | 0}`;
}
requestAnimationFrame(loop);
};
loop();
Also, do not use setInterval and setTimeout for precise timing. These functions are volatile. Use Date.now() instead.
A timer will count down from 10 minutes on loading the page. If I do a mousedown after some time, the countdown should start again.
But then the timer will jump between both values. It seems, that both are counting. How can I remove exiting intervals?
Template.content.onRendered(function() {
var display = document.querySelector('#timer');
startTimer( 600, display);
});
Template.content.events({
'mousedown': function() {
var display = document.querySelector('#timer');
startTimer( 600, display);
// this will start a new counter
// but I want the old one to be replaced
}
});
startTimer = function(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;
}
timer();
setInterval(timer, 1000);
};
Add a new variable in your js
var timer = 0;
Update your code in startTimer function from
setInterval(timer, 1000);
to
timer = setInterval(timer, 1000);
And then in your mousedown event handler function, add following line
clearInterval(timer);