<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
</head>
<body>
<div id="timer">
Time Left: 00:<input id="minutes" type="text" style="width: 20px; border: none; background-color:none; font-size: 16px; font-weight: bold;">:<input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;">
</div>
<script>
countdown();
</script>
In this java script code the timer get executing after the time is over and time goes in minus example (00-1:30).
So I want to stop the timer when it reaches the 00:00. And it should give alert when the time is completed or submit the page.
There are a couple of issues, the biggest being that you are testing the seconds and not seconds.value, so you are always entering the else block. However, you also don't have a condition for when it reaches zero. Here is a jsfiddle that should fix those things, http://jsfiddle.net/psQb5/.
there are two possibilities. One is to use the function setInterval instead of setTimeout. Like this.
<script type="text/javascript">
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
var intervalVar;
function countdown() {
intervalVar = setInterval('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
if (secs == 0) {
window.clearTimeout(intervalVar);
alert('timeout');
}
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
use setInterval() function instead of setTimeout().
when you want to stop timer using clearInterval() function.
for basic understanding of above function click below
w3schools.
Related
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>
So I was trying to write some javascript to countdown and then submit the form when the countdown is finished. This is the JS I found online and tried to implement:
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
Here it is implemented:
https://jsfiddle.net/spadez/9p9o4k6s/1/
The error says: secondPassed is not defined but I'm not sure why that is. Could anyone please explain where I have gone wrong?
For me both ways of calling setInterval work well with SO snippet. I think bug can be jsfiddle specific as it seems it accepts only the first form of setInterval, which takes function and interval, not code string to execute and delay (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval). If you want to keep using fiddle you will have to change last line to:
var countdownTimer = setInterval(secondPassed, 1000);
var seconds = 300;
function secondPassed() {
var minutes = Math.round((seconds - 30) / 60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.qForm.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
body {
background-color: #eee;
}
canvas {}
time {color: red; float: right;}
.active {color: green; font-size: 12px; font-weight: bold;}
<h3>Question 1 of 20<time id="countdown">5:00</time></h3>
<form name="qForm">
<input type="radio"> 219
<input type="submit" value="Submit">
</form>
There is an error in last line of your code. Change that line to this'
var countdownTimer = setInterval(secondPassed, 1000);
Here is the updated fiddle. https://jsfiddle.net/9p9o4k6s/3/
When you pass a function call as a string to setInterval like that, the function you're calling must be in the global scope. Your function secondPassed is wrapped by the jsFiddle onload wrapper and so it is not in the global scope.
To demonstrate this, if you did window.secondPassed = secondPassed; to put it in the global scope, your existing code would work.
The proper solution is to pass the function object as the argument instead of a string:
var countdownTimer = setInterval(secondPassed, 1000);
Note there are no parenthesis () when used in this way.
I can't seem to figure out why my countdownclock function keeps restarting after reaching 00:00. It gets to 00:00 but then restarts from whatever I put in the prompt. I believe I need to add a condition such as a while #time != "00:00" but I'm not entirely sure how.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
You need to clear the interval. Set the interval to a variable and clear it when it's finished otherwise, it will keep on going.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
var interval;
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
clearInterval(interval);
}
};
// we don't want to wait a full second before the timer starts
timer();
interval = setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
You need to store the interval in a variable and clear it when total time gets to 0.
Working solution.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds,
countDownTimer;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
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) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
clearInterval(countDownTimer);
}
}
// we don't want to wait a full second before the timer starts
timer();
countDownTimer = setInterval(timer, 1000);
}
window.onload = function() {
var choice = prompt("Minutes to launch")
var setTheClock = 60 * choice,
display = document.querySelector('#time');
startTimer(setTheClock, display);
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body style="width: 100vw; padding: 0; border: 0; margin: 0;">
<div style="width: 60vh; padding: 0; border: 0; margin: 0 auto;">
<p id="time" style="font-family:futura; font-size: 20vh; text-align: center; padding: 0; border: 0; margin-top: 40vh"></p>
</div>
</body>
</html>
I am trying to make an easy countdown but it does not work the way I think it should work. This is the first time I use setInterval in Javascript and would be very happy if someone could find my mistake.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function timer () {
window.clearTimeout(clock)
var seconds = 10;
var clock = setInterval(function() {
if (seconds == 0) {
} else {
seconds = seconds-1;
document.getElementById('seconds').innerHTML = seconds;
};
},1000);
}
</script>
<button onclick="timer();">timer</button>
<p id="seconds">10</p>
</body>
</html>
I hoped the timer would start-over when you clicked the button, but there are 2 timers running at the same time.
There are several problems with your code you need to address:
You need to make the clock variable global. In your example, an empty new variable clock is created each time the timer() function is called.
You are using the clearTimeout() function instead of the clearInterval() function.
The setInterval() function may miss some ticks and your seconds counter will then be off. If you wish to avoid that, you should check the current time each time the interval function is called.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var clock;
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(10 - (new Date().getTime() - start) / 1000);
if (seconds > 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
}, 1000);
}
</script>
<button onclick="timer();">timer</button>
<p id="seconds">10</p>
</body>
</html>
A breakdown of Math.round(10 - (new Date().getTime() - start) / 1000):
new Date().getTime() returns the current time in milliseconds since the epoch.
(... - start) / 1000 returns the number of seconds since the start of the timer.
10 - ... returns the number of remaining seconds.
Math.round(...) rounds the result to an integer.
Just using setTimeout simplifies things (you used setInterval, but clearTimeout to clear it), declare the necessary variables outside the timer function and add a reset argument to be able to reset the timer.
(function () {
var report = document.querySelector('#seconds');
var seconds = 10;
var timed = null;
document.querySelector('button')
.addEventListener('click', function(e) { timer(true) });
timer(true);
function timer (reset) {
seconds -= 1;
if(reset) {
clearTimeout(timed);
seconds = 10;
}
report.textContent = seconds;
if (seconds > 0 ) {
timed = setTimeout(timer, 1000);
}
}
}())
#seconds {
font: 48px/70px bold verdana, arial;
color: white;
width: 70px;
height: 70px;
background: green;
text-align: center;
border-radius: 50%;
}
<button>start/reset timer</button>
<p id="seconds"></p>
Added:
Ok to add some additional details as I thought you had to keep the questions concise
but it has been downvoted for lack of research. This script was about the third or fourth
that I had tried to do what I wanted and work across the various browsers. When it did
not work I did search for resources to help and thought it may be the way the countdown is output in that IE doesn't like the Input ID so tried other ways to display it but couldn't get it to work hence the question. There is no error displayed one IE it just doesn't show anything - hence it is just a guess about the input id.
I found this Javascript code - maybe even off here and it does exactly what I want
and shows up fine in FF & Chrome. Unfortunately though it doesn't show the countdown
at all in IE and wondered if there is any way of changing the way the countdown is
output that would be compatible with IE.
Here's the code i'm using:
<script type="text/javascript">
// set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
And displaying it like this:
<div id="timer">
Time Ending In: <input id="minutes" type="text"> minutes and <input id="seconds" type="text"> seconds.
</div>
<script>
countdown();
</script>
As I say the above displays fine in FF & Chrome - is there any way to get it to work in IE?
Thanks in advance.
<script type="text/javascript">
var minutes, seconds;
// set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
<div id="timer">
Time Ending In: <input id="minutes" type="text"> minutes and <input id="seconds" type="text"> seconds.
</div>
<script>
countdown();
</script>
<script type="text/javascript">...
var minutes, seconds;
...