I can't get the second countdown function to work correctly in the first Snippet. I fire off cdtd(); a second time for that. Both cdtd(); functions do not collide and are in inside anonymous functions. When I fire off cdtd(); the first time I get a working countdown timer until 16:00:00. When I fire off it for the second time I will not get a working countdown timer until 17:00:00. This is the actual use case of this question.
Just to made an example flow I made a second snippet. Both cdtd(); do collide eachother but the second cdtd(); function call will give a working countdown timer back. Now I still don't know why it's not working in the first snippet. Havint there a timeOut function I work with.
I'm not sure what is wrong. Anyone has got a clue?
Here is the script. https://jsfiddle.net/3fq2j6a1/
I tried to run the countdown scripts under eachother and that works but I don't need that :) function cdtd() { .. }
Here is a snippet:
// First session
var sessie1 = new Date();
var totsessie1 = new Date(sessie1.getFullYear(), sessie1.getMonth(), sessie1.getDate(), 14, 16, 0, 0) - sessie1;
if (totsessie1 < 0) {
totsessie1 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// First countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 16, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End first countdown
}, totsessie1);
// Second session
var sessie2 = new Date();
var totsessie2 = new Date(sessie2.getFullYear(), sessie2.getMonth(), sessie2.getDate(), 14, 17, 0, 0) - sessie1;
if (totsessie2 < 0) {
totsessie2 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// Second countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 17, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End second countdown
}, totsessie2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
Here is the snippet of the code when I use the countdown scripts under eachother.
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 15, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " min and " + seconds + " seconds to go! (countdown to line 49)";
timer = setTimeout(cdtd, 1000);
}
cdtd();
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 16, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " min and " + seconds + " seconds to go! (countdown to line 49)";
timer = setTimeout(cdtd, 1000);
}
cdtd();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
https://jsfiddle.net/edfcLzhw/
But I need them inside the session blocks. When doing that I will get a different time left with the second countdown timer. totsessie1(); totsessie2();
The countdown script comes from: Javascript countdown defined with hours
I solved this for now. I did not make the code correctly on 2 points.
First thing. I used the function totsessie1() also being the second totsessie1() function. I changed the second to totsessie2(). I also didn't use clearInterval(timer); before running the second cdtd();.
Here is a working snippet of the end goal:
// First session
var sessie1 = new Date();
var totsessie1 = new Date(sessie1.getFullYear(), sessie1.getMonth(), sessie1.getDate(), 15, 25, 0, 0) - sessie1;
if (totsessie1 < 0) {
totsessie1 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// First countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(),now.getMonth(),now.getDate(),16,0,0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End first countdown
}, totsessie1);
// Second session
var sessie2 = new Date();
var totsessie2 = new Date(sessie2.getFullYear(), sessie2.getMonth(), sessie2.getDate(), 15, 26, 0, 0) - sessie2;
if (totsessie2 < 0) {
totsessie2 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// Second countdown
clearInterval(timer);
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(),now.getMonth(),now.getDate(),17,0,0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End second countdown
}, totsessie2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
</body>
</html>
JSFiddle: https://jsfiddle.net/nwvk8h12/
Related
I want to create countdown timer for hour,minute and second when a button click. This is my code so far.
HTMLcode
<div class="colomn" style="margin-right: 20px">
<button class="start" onclick="clock();">Start</button>
</div>
javascript function
<script>
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 5;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
}
}
}
</script>
This is simple and not showing separate hour,min and sec. How can I apply this for count hour,min and sec. Please help me.
Working Code:
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// 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 an the count down date
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("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
Simple Answer would be as follows,
html part,
<button onclick="clockStart()">Start</button>
<p id="demo"></p>
JS part,
function clockStart() {
setInterval(function() {
date = new Date()
let hour = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
document.getElementById("demo").innerHTML = hour + ":"+ minutes + ":" + seconds;
}, 1000);
}
You need a counter for seconds. During each 1 second interval, decrement this counter, and do the necessary calculations.
var myTimer;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 3610; //Initially set to 1 hour
function myClock() {
--c
var seconds = c % 60; // Seconds that cannot be written in minutes
var secondsInMinutes = (c - seconds) / 60; // Gives the seconds that COULD be given in minutes
var minutes = secondsInMinutes % 60; // Minutes that cannot be written in hours
var hours = (secondsInMinutes - minutes) / 60;
// Now in hours, minutes and seconds, you have the time you need.
console.clear();
console.log(hours + ":" + minutes + ":" + seconds)
if (c == 0) {
clearInterval(myTimer);
}
}
}
clock();
Put it in a fiddle as well. See if it works..
EDIT: Updated the erroneous code. Thanks to #JDrake for pointing the fact out...
You can convert the value in seconds to one in hours, minutes, and seconds:
var secs = Math.floor(c % 60);
var mins = Math.floor((c/60) % 60);
var hours = Math.floor((c/(60*60)));
This will yield you the amount of seconds left over when removing the minutes (using the modulus operator) and then repeats this for the minutes and hours. You can also easily extend this to include days or weeks:
var hours = Math.floor((c/(60*60)) % 24);
var days = Math.floor((c/(60*60*24) % 7);
var weeks = Math.floor((c/60*60*24*7));
Your code does suffer from one downside: if for some reason the calls become slightly further apart, this might increasingly build a delay. You might instead want to use the lines:
endTime = Date.parse(new Date()) + delay;
timeLeft = endTime - Date.parse(new Date());
You can try this;
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- This will start a timer for 5 hours 6 minutes and 7 seconds -->
<button onclick="countdown(5,6,7)"> Start </button>
<div><h3 id="timer"></h3></div>
<script>
function countdown(hr,mm,ss)
{
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
ss--;
if(ss == 0)
{
ss = 59;
mm--;
if(mm == 0)
{
mm = 59;
hr--;
}
}
if(hr.toString().length < 2) hr = "0"+hr;
if(mm.toString().length < 2) mm = "0"+mm;
if(ss.toString().length < 2) ss = "0"+ss;
$("#timer").html(hr+" : "+mm+" : "+ss);
},1000)
}
</script>
Here is a very primordial clock for you:
function clock(t){
if(clock._stop){return};
var d = new Date(Date.now());
console.log(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds())
window.requestAnimationFrame(clock);
}
clock._stop = false;
clock();
check your console. To stop the clock do clock._stop = true; To start it, set it back to false and call like clock(). You can wrap the logic inside an other object with getters/setters or whatever you prefer.
FIDDLE
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="8888888">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
<!DOCTYPE HTML>
<html>
<body>
<p id="demo"></p>
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var countDownDate = new Date("Sep 25, 2025 15:00:00").getTime();
// 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 an the count down date
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("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>
I am currently developing a website with a countdown timer at the headline: http://iphone.myhandykey.com/
The current timer is just 12hrs + few mins.. What I would like is the countdown timer will show the time remaining until 11PM on the Time Zone of the current visitor. Is that possible? Thanks!
Here is the JavaScript:
function startTimer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt(((timer / 60) / 60 ) % 60, 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.textContent = hours + ":" + minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var onehour = 60 * 600 * 1.231,
display = document.querySelector('#time');
startTimer(onehour, display);
};
Here is the HTML:
<span id=time></span>
EDIT: If the visitor's current time is for example 11:40pm, It should display 23hrs & 20mins left..
(function() {
var start = new Date;
start.setHours(23, 0, 0); // 11pm
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML =
hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
Only <span id='time'></span> left!
Something like this:
$(document).ready(function () {
var mg = new Date(2016, 5, 21, 0, 0, 0, 0);
var tmr = window.setInterval(function () {
var d = new Date();
var dif = mg - d;
var s = parseInt(dif / 1000);
if (s < 0) {
document.getElementById('spCnt').innerHTML = 'Event starts';
window.clearInterval(tmr);
return;
}
var sec = s % 60;
var m = parseInt(s / 60);
var min = m % 60;
var h = parseInt(m / 60);
var hour = h % 24;
d = parseInt(h / 24);
document.getElementById('spCnt').innerHTML = d + ' days ' + hour + ' hours ' + min + ' min and ' + sec + ' sec remaining';
}, 1000);
});
I was just wondering with this, how can I get it to display only seconds when minutes hit zero?
So instead of displaying "0 minutes and 41 seconds"
I would like it to only display "41 seconds"
Is this possible?
<script type="text/javascript">
var count = <? = $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = minutes + " minutes and " + seconds + " seconds";
}
</script>
Simplest would be
document.getElementById("clock").innerHTML = (minutes?minutes+ " minutes and ":"")+ seconds + " seconds";
Try this
<script type="text/javascript">
var count = <?= $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer()
{
count = count - 1;
if(count == -1)
{
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
if (minutes > 0) {
min = minutes + " minutes and ";
}
else {
min = "";
}
document.getElementById("clock").innerHTML = min + seconds + " seconds";
}
</script>
I have an requirement to create a timer in that will show up in the alertbox of javascript and it will start counting back from 4 minutes to 0.. The moment time is over , it should stop the timer. Everything I want this to be created in Javascript. I have tried with following code that I got from this link:
Timer in Javascript
But it is not working with me. I have done this::
<script>
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
</script>
<div class="page">
<div id='timer' style="float: left; width: 50%; background-color: red; color: white;"></div>
</div>
I hope, it will help you.
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
Comments are there where I had done changes. Also you need to modify your code as per requirement as alert message is display after every moment when seconds equal to 0 whether time is remaining. I didn't know your requirement about this I didn't touch that code.
Please follow this link for live demo.
Hi I'm trying to add several javascript countdowns to a single html page. I have included the .js file below. Right now my page only displays the first countdown.
function cdtd () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd()',1000);
}
function countdown () {
var end = new Date("May 31, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('countdown()',1000);
}
function cdtd3 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd3()',1000);
}
function cdtd4 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd4()',1000);
}
function cdtd5 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd5()',1000);
}
function cdtd6 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd6()',1000);
}
There are several problems you need to fix here:
Each of your countdown timers uses the same element IDs when it stores the time strings. That's why only one of them shows up.
If any of your countdowns reaches zero, the document.write() call will erase the entire page.
The code is repeated over and over again. This should be one common function for all your countdowns. (What if you need to add one more? Ten more?)
While multiple timers would work, you don't need them. Run a single timer and update all your displayed times from it.
When you call setInterval(), it's better to pass a function reference as the first parameter instead of a string.
Give those ideas some thought and see what you can come up with, then report back with your new code. :-)
Right now you are referencing one box overwriting each value everytime you call the function.
You want to use a query selector instead of getElementById.
Here is a simple example using jQuery:
var cdtd = function(id,end) {
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$( id + " .days").html(days);
$( id + " .hours").html(hours);
$( id + " .minutes").html( minutes);
$( id + " .seconds").html( seconds );
console.log(id + " .hoursBox",$( id + " .hoursBox").length,id,end,hours,minutes,seconds)
var timer = setTimeout(function(){cdtd(id,end)},1000);
}
cdtd("#counter1",new Date("December 25, 2014 00:01:00"));
cdtd("#counter2",new Date("October 31, 2014 00:01:00"));
cdtd("#counter3",new Date("January 1, 2014 00:01:00"));
http://plnkr.co/8LrtWvfGnZWyRYl2RlWd
#Shanimal i m used this code on my website,problem is that when timer reached 0000 then it goes another page and shows deal ended.what i want ,when timer reach 0000 it should must display message on same page on specific div.it should not go for another page.i have tried it by removing
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
it does not shows any message even when it reached 0000 it start to count again from -1 - 1 -1 -1