// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance/1000/60)%60);
var seconds = Math.floor((distance /1000) % 60);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
I want the output with 2 numbers in minute and 2 numbers in seconds like 09:06
I tried with slice(-2) but it didn´t work properly, so i want to know other options to try
Im so newbie with js and this things
Just check if it's under 10 and if so add a leading 0:
var minutes = (Math.floor((distance/1000/60)%60)<10?'0':'') + Math.floor((distance/1000/60)%60);
var seconds = (Math.floor((distance /1000) % 60)<10?'0':'') + Math.floor((distance /1000) % 60);
There are a few ways to do this.
Check if number is less than 10 and prepend 0 if so
function checkTime(num){
if(num<10){
return "0"+num
}
return num
}
<body>
<div>Expires In <span id="time">05:00</span> minutes!</div>
</body>
<script>
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 () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance/1000/60)%60);
var seconds = Math.floor((distance /1000) % 60);
// Output the result in an element with id="demo"\
if (minutes.toString().length == 1)minutes= "0" + minutes;
if (seconds.toString().length == 1)seconds= "0" + seconds;
document.getElementById("demo").innerHTML = minutes+":"+seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance / 1000 / 60) % 60);
var seconds = Math.floor((distance / 1000) % 60);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = ("0" + minutes).slice(-2) + "m " + ("0" + seconds).slice(-2) + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1);
</script>
</body>
</html>
Replace the following line in your code
document.getElementById("demo").innerHTML = minutes + "m " + seconds + "s ";
with
document.getElementById("demo").innerHTML = ("0" + minutes).slice(-2) + "m " + ("0" + seconds).slice(-2) + "s ";
Explanation :
In the code, you need to prepend every digit with a “0” and return the last two characters with slice(-2). This way JavaScript will add a leading zero to every one-digit number but leave two-digit numbers intact.
For example:
(“05”).slice(-2) = “05”;
(“018”).slice(-2) = “18”;
Related
var date = new Date;
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
setTimeout(function () {
$('#offer1').fadeOut('fast');
$('#remainingTime').fadeOut('fast');
}, 8640000);
function Timer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt((timer / 3600) % 24, 10)
minutes = parseInt((timer / 60) % 60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(parseInt(hours-h) + ":" + parseInt(minutes-m) + ":" + parseInt(seconds-s));
--timer;
}, 1000);
}
jQuery(function ($) {
var twentyFourHours = 24 * 60 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
});
var i =$("remainingTime").textContent;
console.log(i);
<div class="ml-2">Time Remaining <span id="remainingTime">24:00:00</span></div>
<div id="offer1">asdf</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
Here, I've made a timer which says how much time is left for 24 Hours.
But it's showing Hours, Minutes and seconds in negative value for seconds after a minute and negative value for minutes after an Hour.
I need the both div elements ("offer1" and "remainingTime") should fade out after 24 hours timer.
By using the current Date and getTime() I should show the time remaining
Here is the JSFiddle Link https://jsfiddle.net/Manoj07/d28khLmf/2/...
Thanks for everyone who tried to help me. And here is the answer
https://jsfiddle.net/Manoj07/1fyb4xv9/1/
Hello this code works for me
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="ml-2">Time Remaining <span id="remainingTime"></span></div>
<div id="offer1">asdf</div>
<script>
// this code set time to 24 hrs
var timer2 = "24:00:00";
/*
if you want to get timer from localstorage
var session_timer = localStorage.getItem('timer');
if(session_timer){
console.log('timer',session_timer);
timer2 = session_timer;
}
*/
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if (hours < 0) clearInterval(interval);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours+ ':' +minutes + ':' + seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('finish')
// fade out div element
$( "#offer1" ).fadeOut( "slow", function() {
// Animation complete.
});
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>
createCountdown returns a countdown object with two methods: start and stop.
A countdown has a to date, an onTick callback, and a granularity.
The granularity is the frequency at which the onTick callback is invoked. So if you set a granularity of 1000ms, then the countdown will only tick once a second.
Once the difference between now and to is zero, the onComplete callback is called, and this hides the DOM node.
This solution uses requestAnimationFrame which will have a maximum resolution of about 16 milliseconds. Given that this is the maximum speed that the screen is updated, this is fine for our purposes.
const $ = document.querySelector.bind(document)
const now = Date.now
const raf = requestAnimationFrame
const caf = cancelAnimationFrame
const defaultText = '--:--:--:--'
const createCountdown = ({ to, onTick, onComplete = () => {}, granularityMs = 1, rafId = null }) => {
const start = (value = to - now(), grain = null, latestGrain = null) => {
const tick = () => {
value = to - now()
if(value <= 0) return onTick(0) && onComplete()
latestGrain = Math.trunc(value / granularityMs)
if (grain !== latestGrain) onTick(value)
grain = latestGrain
rafId = raf(tick)
}
rafId = raf(tick)
}
const stop = () => caf(rafId)
return { start, stop }
}
const ho = (ms) => String(Math.trunc((ms/1000/60/60))).padStart(2, '0')
const mi = (ms) => String(Math.trunc((ms%(1000*60*60))/60000)).padStart(2, '0')
const se = (ms) => String(Math.trunc((ms%(1000*60))/1000)).padStart(2, '0')
const ms = (ms) => String(Math.trunc((ms%(1000)))).padStart(3, '0')
const onTick = (value) => $('#output').innerText = `${ho(value)}:${mi(value)}:${se(value)}:${ms(value)}`
const onComplete = () => $('#toFade').classList.add('hidden')
const to = Date.now() + (2 * 60 * 1000)
const { start, stop } = createCountdown({ to, onTick, onComplete })
$('button#start').addEventListener('click', start)
$('button#stop').addEventListener('click', () => (stop(), $('#output').innerText = defaultText))
div#toFade {
opacity: 1;
transition: opacity 5s linear 0s;
}
div#toFade.hidden {
opacity: 0;
}
div {
padding: 20px;
}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="output">--:--:--:--</div>
<div id="toFade">This is the element to fade out.</div>
See https://www.w3schools.com/howto/howto_js_countdown.asp for the code used to create a countdown timer
See how to get tomorrow's date: JavaScript, get date of the next day
// Set the date we're counting down to
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = tomorrow - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
hours = ("00" + hours).slice(-2);
minutes = ("00" + minutes).slice(-2);
seconds = ("00" + seconds).slice(-2);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = 'Time Remaining: '+hours + ":"
+ minutes + ":" + seconds;
// If the count down is over, hide the countdown
if (distance < 0) {
$("#demo").hide();
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
I am building an e-commerce website.
And I want to create a countdown timer.
What I wanna do is to start the count down from 23:59:59 to 00:00:00.
And once the timer ends at 00:00:00, I want to restart the timer from 23:59:59 again.
So I have to use a loop.
Now I created count down timer which does not loop.
It starts from 2019/06/14 00:00:00, and ends 2019/06/17 23:59:59.
After it finishes to count down, the message is shown in the display that the campaign is ended.
app.js
function CountdownTimer(elm, tl, mes) {
this.initialize.apply(this, arguments);
}
CountdownTimer.prototype = {
initialize: function (elm, tl, mes) {
this.elem = document.getElementById(elm);
this.tl = tl;
this.mes = mes;
},
countDown: function () {
var timer = '';
var today = new Date();
var day = Math.floor((this.tl - today) / (24 * 60 * 60 * 1000));
var hour = Math.floor((day * 24) + ((this.tl - today) % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
var min = Math.floor(((this.tl - today) % (24 * 60 * 60 * 1000)) / (60 * 1000)) % 60;
var sec = Math.floor(((this.tl - today) % (24 * 60 * 60 * 1000)) / 1000) % 60 % 60;
var milli = Math.floor(((this.tl - today) % (24 * 60 * 60 * 1000)) / 10) % 100;
var me = this;
if ((this.tl - today) > 0) {
if (hour) timer += '<span class="cdt_num">' + hour + '</span><small>hours</small>';
timer += '<span class="cdt_num">' + this.addZero(min) + '</span><small>minutes</small><span class="cdt_num">' + this.addZero(sec) + '</span><small>seconds</small><span class="cdt_num">' + this.addZero(milli) + '</span>';
this.elem.innerHTML = timer;
tid = setTimeout(function () {
me.countDown();
}, 10);
} else {
this.elem.innerHTML = this.mes;
return;
}
},
addZero: function (num) {
return ('0' + num).slice(-2);
}
}
//
function CDT() {
var myD = Date.now();
var start = new Date('2019-06-14T00:00+09:00');
var myS = start.getTime();
var end = new Date('2019-06-17T23:59+09:00');
var myE = end.getTime();
if (myS <= myD && myE >= myD) {
var text = '<span>Until the end</span>';
var tl = end;
}
else if (myS > myD) {
var text = '<span>Start</span><span>from</span>';
var tl = start;
}
else {
var text = "";
}
var timer = new CountdownTimer('cdt_date', tl, '<small>ended</small>');
timer.countDown();
target = document.getElementById("cdt_txt");
target.innerHTML = text;
}
window.onload = function () {
CDT();
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>timer</title>
</head>
<body>
<div class="cdt_wrapper">
<div class="cdt-btn">
<div class=cdt>
<span class="cdt_txt" id="cdt_txt"></span>
<br>
<span class="cdt_date" id="cdt_date"></span>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I hope someone knows how to fix these codes to convert DateTime time from 23:59:59 to 00:00:00 and add a loop function.
I'd suggest using moment.js and moment duration format, these make working with dates and intervals a lot easier.
// We can set endTime to whatever we want here (e.g. Midnight today )
// Use moment().endOf('day') to do this.
let endTime = moment().add(24, 'hours');
// Show time remaining now.
showTimeRemaining();
// Set a timer to update the displayed clock every 1000 milliseconds.
setInterval(showTimeRemaining, 1000);
function showTimeRemaining() {
let timeRemaining = moment.duration(endTime.diff(moment()));
document.getElementById("time_remain").innerHTML = "Time remaining: " + timeRemaining.format("hh:mm:ss");
if (moment() > endTime) {
resetTimer();
}
}
function resetTimer() {
console.log("Resetting timer..");
endTime = moment().add(24, 'hours');
}
<h4 id="time_remain">Time remaining: </h4>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.js"></script>
Here's a solution with moment.js
moment().endOf('day').diff() will get you the milliseconds untill the end of the day.
Moment has no built in functions to format duration, so we use a little trick.
moment.utc(X).format('hh:mm:ss') will create a new moment at timestamp X milliseconds that we can format using the format() function.
setInterval(function(){
const timeString = moment.utc(moment().endOf('day').diff()).format('HH:mm:ss')
document.getElementById('timer').innerHTML = timeString;
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div id="timer"></div>
The hh:mm:ss portion of a date can be retrieved from it's ISO string representation :
var end = Date.now() + 3000;
setInterval(function tick() {
document.body.textContent = new Date(Date.now() - end).toJSON().slice(11, 19)
}, 1000)
I'm creating a javascript function to countdown a user selected value. This is my code so far.
function countdownTimeStart() {
var time = document.getElementById("test").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
var x = setInterval(function () {
// Get to days date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
/* var distance = countDownDate;*/
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo1").innerHTML = hours + ": "
+ minutes + ": " + seconds + " ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo1").innerHTML = "00:00:00";
}
}, 200);
}
document.querySelector("button").addEventListener(
"click",
countdownTimeStart
)
<input type = "test" id = "test" value="20:12:40">
<div id="demo1"></div>
<button>start</button>
The problem is countdown is not working properly. The count down time start from another time instead of start from 20:12:40 which comes from input tag.
Please help me to solve this.
if you would like to count down a given time the following should work:
var time = document.getElementById("test").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
function countdownTimeStart() {
var x = setInterval(function () {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
// add leading zero for seconds if seconds lower than 10
if (seconds < 10) {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}, 1000);
}
document.querySelector("button").addEventListener(
"click",
countdownTimeStart
)
<input type = "text" id = "test" value="20:00:01">
<div id="demo"></div>
<button>start</button>
Just set the countDownDate to the current time plus the number of hours, minutes, and seconds into the future you require.
var countDownDate = new Date( date.getTime()
+ parseInt(time[0])*(1000 * 60 * 60) //hours
+ parseInt(time[1])*(1000 * 60) //minutes
+ parseInt(time[2])*1000 ); //seconds
I am trying to display a full screen image after a jQuery countdown timer has finished but I am confused how to do this within my jQuery/css/html scripts
My jQuery code is as follows:
//Sets the date and time the clock is counting down to
var countDownDate = new Date("August 23, 2017 17:43:00").getTime();
//Updates the counter every second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
// Finding the length of time between now and count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance/ (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % ( 1000 * 60)) / 1000);
//Output the result in an element with an id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// if the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = " you've been screwed over by Theresa May";
function myFunction() {
var m = document.getElementsByClassName("image");
m[0].innerHTML = "image";
}
}
}, 1000);
My HTML is as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Brexit Countdown 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href ="Brexit2.css" rel="stylesheet" type="text/css"/>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
<script src="Brexit2.js"></script>
</head>
<body>
<h1>Brexit Countdown</h1>
<p id="demo"></p>
</body>
</html>
My CSS is as follows-
p {
text-align: center;
font-size: 80px;
}
h1 {
text-align: center;
font-size: 200px;
}
As mentioned at the beginning I simply want to display an image along with a statement after the countdown finally finishes. I really would appreciate some help here. Many thanks.
//Consider this function to display the image and the <p>
function myFunction() {
document.getElementById("displayImage").style="display:block";
}
//This calls the myFunction() in the set time.
setInterval(myFunction, 5000);
//5000 is in milliseconds, which is 5 seconds.
<div id="displayImage" style="display:none">
<img src="https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png">
<p>Assume that this is the image you wanna display...</p>
</div>
Please use this JSFiddle as reference. Please set the countDownDate to a future time, else it wont work.
Demo: here
Code:
//Sets the date and time the clock is counting down to
var countDownDate = new Date("August 23, 2017 23:29:00").getTime();
//Updates the counter every second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
// Finding the length of time between now and count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance/ (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % ( 1000 * 60)) / 1000);
//Output the result in an element with an id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// if the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = " you've been screwed over <br> by Theresa May";
var m = document.getElementsByClassName("image");
m[0].src = "https://upload.wikimedia.org/wikipedia/commons/7/79/Operation_Upshot-Knothole_-_Badger_001.jpg";
}
}, 1000);
A common way is to add the image to the html, but to hide it using a css class.
HTML:
<img id="hiddenImage" class="hiddenClass" src="someSource.jpg">
CSS:
.hiddenClass {
display: none;
}
Then, using jQuery or vanilla JS, you either change the CSS class to something else, or to remove the class.
jQuery:
// find by id, the jQuery way
var image = $('#hiddenImage');
// remove the class that was hiding the image before
// this will make it visible by default
image.removeClass('hiddenClass');
JsFiddle Demo: https://jsfiddle.net/jonahe/rxprv1c0/
I'm trying to create a countdown timer in the format of 00:00:00 (minutes, seconds, and hundredths). Right the now the way I set up my countdown timer, is to make sure the user inputs in the format of 00:00:00 (which has to be). From there the countdown time should commence when they click the start button. I see that it does somewhat of a countdown, but I'm not sure what could be the problem with my implementation. The hundredths is not decrementing correctly for some reason. It should start of as 10:00:00 (10 mins) and go to 09:59:99.. 09:59:98, etc.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<script type="text/javascript">
var running = 0;
var hundreds = 0;
function validTime() {
var setTime = document.getElementById("timeEntered").value;
var regex = /^\d{2}:\d{2}:\d{2}$/;
if (regex.test(setTime)) {
document.getElementById("timeAlert").innerHTML = "<span class='valid'>Valid</span>";
return (true);
} else {
document.getElementById("timeAlert").innerHTML = "<span class='error'>Invalid time entered. Please make sure it's in the format 00:00:00</span>";
return (false);
}
}
function correctTime(){
if (validTime()){
countdownTimer();
return true;
}else{
alert("Please correct your inputted time.");
return false;
}
}
function countdownTimer() {
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(parseInt(timeToSeconds) <= 600 ) {
startPause();
}else{
document.getElementById("output").innerHTML = "Sorry. Time range cannot exceed 10 mins.";
}
}
function startPause(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 0){
running = 1;
decrement();
document.getElementById("startPause").innerHTML = "Start/Stop";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
var hundreds = 0;
function decrement(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 1){
var mins = Math.round((timeToSeconds - 30)/60);
var secs = timeToSeconds % 60;
//var hundredths = timeToSeconds % 100;
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundreds;
if (hundreds === 0){
if(timeToSeconds ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
timeToSeconds--;
hundreds = 100;
}
}else{
hundreds--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="mainCont">
<p>Please enter the desired time:
<input type="text" id="timeEntered" onblur="validTime();"> <span id="timeAlert"></span>
</p>
<p>
<button id="startPause" onclick="correctTime()">Start/Stop</button>
</p>
<div id="output">00:00:00</div>
</div>
</body>
</html>
I think #bholagabbar's code needs rewriting into hundreths of a second rather than in seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
dispms=parseInt(timer % 100,10);
seconds = parseInt(timer / 100, 10);
minutes = parseInt(seconds / 60, 10);
seconds = parseInt(seconds % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 10); //hundreths of a second - 1000 would be 1 second
}
window.onload = function () {
var fiveMinutes = 60 * 5 * 100, //hundreths of second
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
I'm not sure if this is what you wanted but I have some working code for a timer that counts up to the given input (in seconds) which includes the 1/100th of a second. If you want to include ms as you mentioned, you will need 3 0's or ':000' for the display int the end. Here is the code. How will of course, have to mod it for your scenario but the timer is implemented perfe
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
dispms=parseInt((timer)%100,10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
I think you will have to make changes only in the HTML part. Rest of the logic in my code is fine for a general timer. You will have to pass in the seconds as an argument, that is all