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>
Related
I have made a countdown but now I want to make a input field with how many minutes the countdown should countdown from. What I have is a pretty basic countdown but what I don't have is that a user puts the amount of minutes into the input field, click the button, and it counts down the minutes. And I hope someone can help me with this.
This is what I got so far:
(()=> {
let countdownEnded = false;
start(3600); // seconds
})();
function start(inputTime){
let startTime = Date.now();
intervalSeconds = setInterval(() => {
let currentTime = Date.now() - startTime;
if(inputTime < 1) {
stop();
} else {
updateDisplay(inputTime, currentTime);
updateMillis();
}
}, 1000);
}
function stop(){
let countDivElement = document.getElementById("countdown"); /*** Updated***/
countDivElement.innerHTML = 'countdown done';
countdownEnded = true; /*** Updated***/
}
function updateDisplay(seconds, currentTime){
let timeIncrement = Math.floor(currentTime / 1000);
updateTime(seconds - timeIncrement);
}
/**
* #method - updatesecondsond
* #summary - This updates the timer every seconds
*/
function updateTime(seconds) {
let countDivElement = document.getElementById("timer");
let minutes = Math.floor(seconds / 60);
let remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds > 0) {
seconds = seconds - 1;
} else {
clearInterval(intervalSeconds);
countdownEnded = true;
countDivElement.innerHTML = 'countdown done';
return null;
}
countDivElement.innerHTML = minutes + ":" + remainingSeconds + ":" ;
};
function updateMillis() {
let countMillsElement = document.getElementById('millis');
let counterMillis = 99;
let millis;
let intervalMillis = setInterval(()=> {
if(counterMillis === 1) {
counterMillis = 99;
} else {
millis = counterMillis < 10 ? '0' + counterMillis : counterMillis;
};
countMillsElement.innerHTML = millis;
counterMillis --;
}, 10);
if(countdownEnded) {
stop(); /*** Updated***/
return clearInterval(intervalMillis);
}
};
<div class="clock" id="model3">
<div id="countdown"> <!-- Updated -->
<span id="timer"></span><span id="millis"></span>
</div>
</div>
<input id="minutes" placeholder="0:00"/>
I think this may help you.
Change the following
<input id="minutes" placeholder="00"/> <button onclick="startTimer()">Start</button>
And in javascript add a new function
function startTimer(){
var x=document.getElementById("minutes").value * 60; //To Change into Seconds
start(x);
}
And remove the start function
Just add a button with click event that takes input value and triggers your 'start' function with that value as parameter. Something like this:
document.getElementById("startBtn").addEventListener("click", startTimer);
function startTimer() {
var numberOfMinutes = Number(document.getElementById("minutes").value) * 60;
start(numberOfMinutes);
}
And remove 'start' function call from the window load to prevent the timer to start immidiately.
Result is something like this:
https://jsfiddle.net/scarabs/6patc9mo/1/
I've got a timer function as follows (which I've just grabbed off a jsfiddle):
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function returnDate(){
return Number(new Date);
}
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (returnDate());
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
I call the function and set it to countdown to 2 minutes like so:
$(".btn-start").click(function(){
countdown("countdown-2-minutes",2,0);
});
I have another element with id countdown-8-minutes that I want to start immediately when the timer on countdown-2-minutes reaches 0. How should I do this? I suppose an okay way would be to monitor when the html on the first element reads "0:00" but I don't exactly know how to implement that.
Here's what I would suggest; First change your countdown() function to accept a callback parameter:
function countdown( elementName, minutes, seconds, callback )
{
var element, endTime, hours, mins, msLeft, time;
function returnDate(){
return Number(new Date);
}
function twoDigits( n )
{
return (n <= 9 ? "0" + n : n);
}
function updateTimer()
{
msLeft = endTime - (returnDate());
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
if (typeof callback === 'function') {
callback.call()
}
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
}
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
then pass that callback with your initial call:
$(".btn-start").click(function(){
countdown("countdown-2-minutes",2,0, function(){countdown("countdown-8-minutes",8,0);});
});
Just call countdown() with the proper parameters when you detect that the timer is finished. Try this:
if ( msLeft < 1000 ) {
element.innerHTML = "0:00";
countdown("countdown-8-minutes",8,0);
}
You don't need to watch the element's content to know when to start the next timer. In fact you're already reacting to that happening on the line you check if ( msLeft < 1000 ) { in which you can start your next timer.
Once your current timer hits zero you can just start the next one inside that if statement.
Alternatively you can separate your timer logic from your element logic using something like this:
// CountdownTimer object. Give it a length (ms) to count to, a period (ms)
// to loop updates to the callback, and a callback (function(done:bool)) that
// handles update ticks where done=false and the final tick where done=true.
function CountdownTimer(length, period, callback) {
this.length = length;
this.period = period;
this.callback = callback;
// Assert the callback to be a function to avoid messy error handling, and
// show we noticed in the console.
if (typeof this.callback !== 'function') {
console.warn('Callback was not a function.');
this.callback = function(){};
}
// Some publically visible variables for time keeping.
this.startTime = 0;
this.elapsed = 0;
this.remaining = length;
// The _loop scope's 'this' is itself. Give it a handle on the CountdownTimer's
// 'this' so we can reference the variables inside the loop.
var scope = this;
// Main loop of the countdown timer.
this._loop = function() {
// Get the number of milliseconds since the countdown started.
scope.elapsed = Date.now() - scope.startTime;
if (scope.elapsed < scope.length) {
// Keep looping if the countdown is not yet finished.
scope.remaining = scope.length - scope.elapsed;
scope.callback(false);
} else {
// Finished looping when the countdown hits or passes the target.
scope.elapsed = scope.length;
scope.remaining = 0;
scope.callback(true);
// Stop the interval timer from looping again.
clearInterval(scope._t);
}
};
}
// This function starts up the CountdownTimer
CountdownTimer.prototype.start = function() {
this.startTime = Date.now();
this._t = setInterval(this._loop, this.period);
}
// Our test elements.
var progress2 = document.getElementById('prog-2m');
var progress8 = document.getElementById('prog-8m');
var clockElement = document.getElementById('clock');
var startButton = document.getElementById('start');
// The 2-minute timer.
var m2 = new CountdownTimer(2 * 60 * 1000, 33, function(done) {
// Calculate the time to display.
var mins = Math.floor(m2.remaining / 60 / 1000);
var secs = Math.floor(m2.remaining / 1000) % 60;
if (secs < 10) secs = '0' + secs;
clockElement.textContent = mins + ':' + secs;
if (done) {
// If we're done, set the timer to show zero and start the next timer.
clockElement.textContent = '0:00';
m8.start();
}
// Progress bar display update.
progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';
});
// The 8-minute timer.
var m8 = new CountdownTimer(8 * 60 * 1000, 33, function(done) {
// Calculate the time to display.
var mins = Math.floor(m8.remaining / 60 / 1000);
var secs = Math.floor(m8.remaining / 1000) % 60;
if (secs < 10) secs = '0' + secs;
clockElement.textContent = mins + ':' + secs;
if (done) {
// Once done, set the timer to zero and display "Done".
clockElement.textContent = '0:00 Done';
}
// Progress bar display update.
progress2.style.width = (40 * (m2.elapsed / m2.length)) + 'px';
progress8.style.width = (160 * (m8.elapsed / m8.length)) + 'px';
});
// Start the 2-minute timer when the button is clicked.
startButton.addEventListener('click', function() {
m2.start();
});
#progress {
width: 200px;
height: 20px;
border: 2px solid #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
border-radius: 2px;
position: relative;
margin: 8px 0;
}
#prog-2m {
width: 40px;
height: 20px;
background-color: #3c9;
position: absolute;
left: 0;
top: 0;
}
#prog-8m {
width: 160px;
height: 20px;
background-color: #c33;
position: absolute;
left: 40px;
top: 0;
}
<div id="progress">
<div id="prog-2m"></div>
<div id="prog-8m"></div>
</div>
<div id="clock">0:00</div>
<button id="start">Begin</button>
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.
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
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