Timer wont stop at 00:00 - javascript

My countdown timer wont stop 00:00 it just keeps going until it reaches " -01:59 " then " -02:59 " and so on , I changed some of the code here and there but it still keeps going and going
<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 ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
</script>
</head>
<body>
<div id="timer">
This is only valid for the next
<input id="minutes" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;"> :
<input id="seconds" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">
</div>
<script>
countdown();
</script>

Here you are: should assign setTimeout to a variable, when secs is 0, clear the time out.
// set minutes
var mins = 1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 10;
var timeout;
function countdown() {
timeout = 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--;
if (secs < 0) {
clearTimeout(timeout);
return;
}
countdown();
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return ("0" + mins).substr(-2);
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return ("0" + (secs - Math.round(mins * 60))).substr(-2);
}
countdown();
<div id="timer">This is only valid for the next
<input id="minutes" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">:
<input id="seconds" type="text" style="width: 60px; border: none; background-color:none; font-size: 50px; font-weight: bold;">
</div>
Hope this helps.

Related

How to make HH:MM:SS countdown timer, using javascript?

i've tried to make simple countdown timer, but i don't know how to make something when the timer ends and i don't know how to make timer with hours HH. I can make only minutes MM and second SS.
So, i have this HTML code:
<div class="tadc-time-display">
<span class="tadc-time-display-hours_minutes">00:00</span>
<span class="tadc-time-display-seconds">00</span>
</div>
The JS code i used to have is useless(
You can use Native JavaScript or jQuery, if you want)
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 fiveMinutes = 60 * 0.1,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
It should also start, stop and reset, but i dont know how to do it( Thanks a lot!
var hours = 0, // obtain these values somewhere else
minutes = 1,
seconds = 20,
target = new Date(),
timerDiv = document.getElementById("timer"),
handler;
function init() {
// set the target date time with the counter values
// counters more then 24h should have a date setup or it wont work
target.setHours(hours);
target.setMinutes(minutes);
target.setSeconds(seconds);
target.setMilliseconds(0); // make sure that miliseconds is 0
timerDiv.innerHTML = target.toTimeString().split(" ")[0]; // print the value
}
function updateTimer() {
var time = target.getTime();
target.setTime(time - 1000); // subtract 1 second with every thick
timerDiv.innerHTML = target.toTimeString().split(" ")[0];
if (
target.getHours() === 0 &&
target.getMinutes() === 0 &&
target.getSeconds() === 0
) { // counter should stop
clearInterval(handler);
}
}
handler = setInterval(updateTimer, 1000);
document.getElementById("stop-button").addEventListener("click", function() {
clearInterval(handler);
});
document.getElementById("start-button").addEventListener("click", function() {
clearInterval(handler);
handler = setInterval(updateTimer, 1000);
});
document.getElementById("reset-button").addEventListener("click", function() {
init();
clearInterval(handler);
});
init();
<div id="timer"></div>
<div>
<button id="start-button">Start</button>
<button id="stop-button">Stop</button>
<button id="reset-button">Reset</button>
</div>
Here is working sample with comments.
try this :
<html lang="en"><head>
<style>
#import "//fonts.googleapis.com/css?family=Bangers";
body {
margin: 0;
}
.wrap {
display: flex;
align-items: center;
justify-content: center;
background:#111;
}
.time-to {
text-align: center;
font-family: Bangers;
color: white;
font-size: 50px;
}
.underline {
text-decoration: underline;
}
.time-to span {
display: block;
font-size: 70px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<div class="wrap ng-scope" ng-app="app">
<div class="time-to">
prochain event dans :
<span countdown="" date="november 17, 2019 15:15:50" class="ng-isolate-scope underline"></span>
<br>
event : minecraft , ip: 144.76.116.78:40020
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script id="rendered-js">
(function () {
angular.module('app', []).directive('countdown', [
'Util',
'$interval',
function (Util,
$interval) {
return {
restrict: 'A',
scope: {
date: '#' },
link: function (scope,
element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
return element.text(Util.dhms(diff));
},
1000);
} };
}]).
factory('Util', [
function () {
return {
dhms: function (t) {
var days,
hours,
minutes,
seconds;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
if(t < 0) {
t = 0
}
if(t === 0) {
t = 0
}
return [days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'].join(' ');
} };
}]);
}).call(this);
</script>
</body></html>

Reset first countdown after the second countdown

Im working on a simple countdown that displays a modal when it is zero, then on that modal there is another countdown, it will close when on zero.
what I want is reset the first countdown again and do the same process.
How can I achieve that?
hope you understand me.
Thanks.
SAMPLE CODE
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
minutes = 00;
seconds = 10;
}
},1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);
Easiest way would be to wrap everything into a function, and call that function again when fadeOut of modal completes.
$('#informationModal').fadeOut(400, startTimer);
function startTimer() {
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function() {
timeleft--;
$('.sec').text(timeleft);
if (timeleft == 0) {
clearInterval(downloadTimer);
$('#informationModal').fadeOut(400, startTimer);
minutes = 00;
seconds = 10;
}
}, 1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);
}
startTimer();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>
This is to give you an idea how you could solve it with scoping your code in a function and then call that function over and over again.
var timer2 = "00 : 00 : 5";
var hour = 0;
var minutes = 0;
var seconds = 0;
var setupTime = function(time){
let timer = time.split(':');
hour = parseInt(timer[0], 10);
minutes = parseInt(timer[1], 10);
seconds = parseInt(timer[2], 10);
}
setupTime(timer2);
var myFunction = function(){
var interval = setInterval(function() {
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0 && seconds < 0) {
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
// resetTimer and call myFunction to start again
setupTime(timer2);
myFunction();
}
},1000);
} else {
$('#countdown').html(seconds);
}
}, 1000);
};
myFunction();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>
You need to be careful with variables if you change them from integers to strings. That's why the time is not visible as 00:00:00 but you will figure out how to solve that.
Side note: If you ask a question. Please always check your indents and fix them as long as you need to provide "clean" code. As it is no fun to fix indents to answer a question.

javascript countdown timer goes negative

I'm trying to implement a countdown timer on my mobile site using javascript. I've got this but the timer goes into negative, it doesn't stop. I want it to stop at 0:0.
JavaScript
// set minutes
var mins = 5;
// calculate seconds
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);
}
HTML
<div id="timer">
This is only valid for the next <input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; font-weight: bold;"> minutes and <input id="seconds" type="text" style="width: 26px; border: none; background-color:none; font-size: 16px; font-weight: bold;"> seconds.
</div>
And I'm also trying to change the font color countdown minute to red but it doesn't seem to change?
<input id="minutes" type="text" style="width: 14px; border: none; background-color:transparent; font-size: 16px; **font-color:red;** font-weight: bold;">
You are unconditionally setting setTimeout to repeat. Try if( secs > 0) setTimeout(Decrement,1000)
The CSS is color, not font-color
Your code is a mess too...
var time = 5 * 60,
start = Date.now(),
mins = document.getElementById('minutes'),
secs = document.getElementById('seconds'),
timer;
function countdown() {
var timeleft = Math.max(0, time - (Date.now() - start) / 1000),
m = Math.floor(timeleft / 60),
s = Math.floor(timeleft % 60);
mins.firstChild.nodeValue = m;
secs.firstChild.nodeValue = s;
if( timeleft == 0) clearInterval(timer);
}
timer = setInterval(countdown, 200);
<div id="timer">
This is only valid for the next <strong id="minutes">-</strong> minutes and <strong id="seconds">-</strong> seconds.
</div>
I did a quick simple counter you can use for your own sake
var mins=5;
var secs = mins*60;
var timerInterv = setInterval(doCountDown, 1000);
var outMins,outSecs
function doCountDown()
{
--secs;
if (secs<=0)
{ outMins=outSecs=0;
clearInterval(timerInterv);
return;
}
outMins = parseInt(secs/60);
outSecs = secs%60;
console.log("M:"+outMins+" S:"+outSecs);
}
You have to add check before decrementing secs
if (secs > 0) {
secs--;
setTimeout('Decrement()', 1000);
}
for font color add color:red in your style that refers on minutes

How to make javascript timer reload

I have this code of Javascript that i got from a forum for my html page:
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 0.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">
Minutes:<input id="minutes" type="text" style="width: 14px; 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;"> seconds.
</div>
<script>
countdown();
</script>
My question is how can i make it reload when the time is up. so if seconds and minuets = 0, it would reload.
Or if you have a better simple times, please show me how :)
add the following lines in countdown:
if (getseconds() == 0 && getminutes() == 0) {
document.location.reload(true)
}
A more simple (and more beautiful) solution:
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
// set minutes
var mins = 0.1;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
secs = secs - 1;
if (secs < 0) {
document.location.reload(true);
} else {
document.getElementById('countdown').innerHTML = secs;
window.setTimeout('countdown()', 1000);
}
}
window.onload = countdown;
</script>
</head>
<body>
Reloading in <span id="countdown"> </span> seconds.
</body>
</html>

how to resume and pause a timer using one button in javascript?

i want to create a timer with pause and resume in one button in JavaScript...
timer is working fine.pause and resume is working fine if it is 2 different button.but if we make into single button resume is not happening .Need help...
JavaScript:
paused = false;
// set minutes
var mins = 30;
// calculate the seconds
var secs = mins * 60;
var t = 0;
function countdown() {
t = 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--;
t = 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);
}
function pause() {
clearTimeout(t);
document.getElementById('Pause').value = "Resume";
document.getElementById("Pause").onclick = resume();
}
function resume() {
t = setTimeout();
}
HTML:
<head>
<title>Countdown</title>
<script src='myscript'></script>
</head>
<body>
<div id="timer">
<input id="minutes" style="width: 24px; border: none; background-color:none;>mts
<input id=" seconds " style="width: 26px; border: none; background-color:none;>second
<div id="timer">
<input type="button" id="Pause" value="Pause" onClick="pause();" />
</div>
</div>
<script>
countdown();
</script>
</head>
Problem is in your resume function
It should be like that
Try this code
<html>
<head>
<title>Countdown</title>
<script type="text/javascript">
paused = false;
// set minutes
var mins = 30;
// calculate the seconds
var secs = mins * 60;
var t=0;
var flagTimer='resume';
function countdown() {
t = 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--;
t= 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);
}
function pause() {
if( flagTimer=='resume')
{
clearTimeout(t);
t=0;alert(' 12c ya');
document.getElementById('Pause').value="Resume";
flagTimer='pause';
}
else
{
flagTimer='resume';
document.getElementById('Pause').value="Pause";
resume();
}
}
function resume() {
t= setTimeout('Decrement()',1000);
}
</script>
</head>
<body>
<div id="timer">
<input id="minutes" style="width: 24px; border: none; background-color:none;">mts
<input id="seconds" style="width: 26px; border: none; background-color:none;"/>second
<div id="timer">
<input type="button" id="Pause" value="Pause" onClick="pause();" />
</div>
</div>
<script>
countdown();
</script>
</body>
</html>
Live Test http://jsbin.com/ajegas/8
Fiddle http://jsfiddle.net/hB5E9/1/
in the pause function after you cleared your timer, set the variable t = 0; and then create a function pausePlay() which checks if(t) pause(); else play();
call pausePlay onClick

Categories