Seconds to minutes and seconds countdown - javascript

I currently have a JS code that takes the amount of seconds and make a live countdown, but I would like to convert the seconds to minutes and seconds, so instead of it saying: You have to wait 602 seconds, I would like to to say: You have to wait 6 minutes and 2 seconds.
This is my javascript:
function timeleft(timeleft_sec, elementID){
var timeleft = timeleft_sec;
var downloadTimer = setInterval(function(){
timeleft--;
document.getElementById(elementID).textContent = timeleft;
if(timeleft <= 0)
location.reload();
},1000);
}
This is my HTML:
You have to wait <t id="countdowntimer">602</t> seconds
<script> timeleft(602, "countdowntimer"); </script>
I have tried googling but I can only find answers where it count down from a certain date, not an amount of seconds.

602 seconds equal to 10 minutes and two seconds
So time counting is starting from 10 minutes and 2 seconds.
function timeleft(timeleft_sec, elementID) {
var timeleft = timeleft_sec;
var downloadTimer = setInterval(function () {
timeleft--;
document.getElementById(elementID).textContent = secondToMinutes(timeleft);
if (timeleft <= 0)
location.reload();
}, 1000);
}
function secondToMinutes(totalSeconds) {
let minutes;
let seconds;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds - minutes * 60;
return `${minutes} minutes and ${seconds} seconds`;
}
timeleft(602, "countdowntimer");
You have to wait <t id="countdowntimer">10 minutes and 2 seconds</t>

Use this function to convert the time -
function convertTime(seconds){
let minutes = 0;
while(seconds > 59) {
minutes++;
seconds -= 60;
}
return `${minutes} min ${seconds} sec`;
}
document.getElementById("time").innerText = convertTime(602);
<div id="time"></div>

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>

Javascript timer ends incorrectly

Looking for some insight on why my javascript timer doesn't work correctly. Actually it works great except for the fact that it stops with 1 second left and displays an alert. When you hit the ok button it counts down to the final second (0) and displays the alert again. I can't figure out how to stop the alert occuring at 1 second left instead of only at zero seconds...
I altered the code to run at 6 seconds instead of the full ten minutes
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;
if (--timer < 0) {
alert('Time has exceeded');
location.href = "http://nova.umuc.edu/~ct388a13/";
}
}, 1000);
}
window.onload = function() {
var tenMinutes = 60 * .1,
display = document.querySelector('#time');
startTimer(tenMinutes, display);
}
<section>
<p id="transactionTimer">Act fast! This transaction must be completed in <span id="time">10:00</span> minutes</p>
</section>
This is because the JS is exectuted for the DOM update is shown to the user. This has to do with the JS event loop, and can be circumvented by using setTimeout with a very low timeout, ie 1ms. See the code snippet below for a working example
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
setInterval(function() {
--timer
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;
if (timer === 0) {
setTimeout(function(){
alert('Time has exceeded');
location.href = "http://nova.umuc.edu/~ct388a13/";
}, 1);
}
}, 1000);
}
window.onload = function() {
var tenMinutes = 60 * .1,
display = document.querySelector('#time');
startTimer(tenMinutes, display);
}
<section>
<p id="transactionTimer">Act fast! This transaction must be completed in <span id="time">10:00</span> minutes</p>
</section>

How to declare a variable which is equal to 30 seconds in javascript

I'm trying to create a timer for 30 seconds and i'm looking to do this on my own, however I seem to be stuck here:
var Starttime = ( needs to be 30 seconds )
var Timeleft = Starttime - 1
if (Timeleft === 0) {
console.log("TIMER FINISHED BEEP BOOP");
}
and through lots of research still not able to find how to declare variable as a simple 30 seconds of time, and I am aware that I would need to do the same for the 1 ( change it to 1 second). TL;DR how do I write 30 seconds
try this function using setinterval() :
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;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
//this is where you can modifies the time amount.
var minutes= 60 ,
display = document.querySelector('#time');
startTimer(minutes, display);
};
<body>
<div>One minute countdown <span id="time">1:00</span> minutes!</div>
</body>

Javascript Time - Run a Function every Half Hour

I made this function that does two things: returns the amount of time until the next thirty minute mark, and calls the halfHour function when the timer reaches zero. If the time was 12:06:27, output would be 24:33 (mm:ss)
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (60-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (60-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
This works, but there is a strange glitch. When the minute rolls over, it shows...
24:02
24:01
23:00
23:59
23:58
It also calls halfHour(); one minute too soon, at the false 0:00 mark in the last sequence: 1:02 1:01 0:00 0:59
How can we correct this?
Solved
Commenters dbrin and njzk2 have the solution. It's subtracting minutes and seconds from 59 instead of 60. Below is the modified working code. Sorry it's messy.
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (59-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (59-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
Why reinvent the wheel when JavaScript has a built in setInterval(code, delay); to acheive this.
setInterval(function() {
alert("I will fire after every 2 seconds")
}, 2000);
The way you measure the time is flawed. The number of minutes and the number of seconds cannot be considered separately, as I showed in my earlier comment.
An easier way is to start by measuring the total number of seconds, and then format it:
var time = new Date();
var totalS = 60 * ((60 - time.getMinutes()) % 30) - time.getSeconds()
var secs = totalS % 60
var mins = (totalS - secs) / 60

javascript countdown to next real 5 minutes

I need to create a javascript timer that will count down to the next 5 minutes.
For example let's say the time is 00:07:30, the time will say 02:30
if the time is 15:42:00 the timer will say 03:00
I can't really think of any good way to du this.
thank you.
There are many ways to do this. My idea is to find out the reminder of current time divide by five minutes (300 seconds).
Demo : http://jsfiddle.net/txwsj/
setInterval(function () {
var d = new Date(); //get current time
var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet current mm:ss to seconds for easier caculation, we don't care hours.
var fiveMin = 60 * 5; //five minutes is 300 seconds!
var timeleft = fiveMin - seconds % fiveMin; // let's say now is 01:30, then current seconds is 60+30 = 90. And 90%300 = 90, finally 300-90 = 210. That's the time left!
var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds back into mm:ss
document.getElementById('test').innerHTML = result;
}, 500) //calling it every 0.5 second to do a count down
Instead you could try using window.setInterval() like this:
window.setInterval(function(){
var time = document.getElementById("secs").innerHTML;
if (time > 0) {
time -= 1;
} else {
alert ("times up!");
//or whatever you want
}
document.getElementById("secs").innerHTML = time;
}, 1000);
const startMinutes = 1
let time = startMinutes * 60
const updateCountDown = () => {
const t = setInterval(() => {
const minutes = Math.floor(time / 60)
const seconds = time % 60
const result = `${parseInt(minutes)}:${parseInt(seconds)}`
document.getElementById('test').innerHTML = result
time--
if (minutes === 0 && seconds === 0) {
clearInterval(t)
}
}, 1000)
}
If you want to do a timer on your webpage, you can try to use something like this:
<html>
<head>
<script type="text/javascript">
var now = new Date().getTime();
var elapsed = new Date().getTime() - now;
document.getElementById("timer").innerHtml = elapsed;
if (elapsed > 300000 /*milliseconds in 5 minutes*/) {
alert ("5 minutes up!");
//take whatever action you want!
}
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>

Categories