I have made a countdown clock for quiz module so whenever the counter ends up I get a negative value. After the end of the timer I am getting -1 :-1 and I want it as 00:00.
I thought there would be an error in the total time but I am not able to figure out the error
I have tried this logic but it's not working
<script>
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if($('.minutes').text() == '00' && $('.seconds').text() == '00')
{
if(score == 0)
{
// Wrap every letter in a span
document.getElementById("congrats").innerHTML = "Better Luck Next time"; //When all the words are solved, greeting is displayed
document.getElementById("part1").hidden = false;
document.getElementById("goodjob").hidden = false;
document.getElementById("part2").hidden = false;
document.getElementById("button5").disabled = true;
document.getElementById("totscore").innerHTML = "Total correct answer " + score;
document.getElementById("totcoins").innerHTML = "Total coins achieved " + score;
document.getElementById("coins").hidden = false;
document.getElementById("my_audio").pause();
setTimeout(function(){
document.getElementById("drop").play();
}, 1000)
}
else if(score == 5){
document.getElementById("congrats").innerHTML = "Congratulations You solved all three piece words"; //When all the words are solved, greeting is displayed
document.getElementById("part1").hidden = false;
document.getElementById("goodjob").hidden = false;
document.getElementById("part2").hidden = false;
document.getElementById("totscore").innerHTML = "Total correct answer " + score;
document.getElementById("totcoins").innerHTML = "Total coins achieved " + score;
document.getElementById("coins").hidden = false;
document.getElementById("my_audio").pause();
setTimeout(function(){
document.getElementById("drop").play();
}, 1000)
}
}
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 20 * 1000);
initializeClock('clockdiv', deadline);
</script>
My HTML Code
<nav class="navbar navbar-light bg-light fixed-top">
<div class="row" style="width:100%">
<div class="col-md-6">
<div id="clockdiv">
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="score-box" id="scoring">
Your Score is 0
</div>
</div>
</div>
</nav>
Your function runs once more after reaching 0, thus resulting in -1.
You can fix it quickly by making a check in the function to get the remaining time:
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
minutes = minutes < 0? 0 : minutes; //Check if they are lower than 0, if yes, set them to 0
seconds = seconds < 0? 0 : seconds;
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
First of all, don't use the string you put in the html to verify a number, use actual numbers. I'm referring to
if($('.minutes').text() == '00' && $('.seconds').text() == '00')
Avoid doing this.
You put a value inside the object you return from getTimeRemaining that represent the actual difference in milliseconds between the dates. Why not use that?
if (t.total <= 0) {
...
}
You need to check this before you put the time in the HTML.
EDIT: you're actually doing this at the end of updateClock, just check it before printing, and if <= 0 manually set the html to read 00:00.
function updateClock() {
var t = getTimeRemaining(endtime);
if (t.total <= 0) {
clearInterval(timeinterval);
minutesSpan.innerHTML = '00';
secondsSpan.innerHTML = '00';
if(score == 0) {
...
}
....
} else {
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
}
}
Related
Countdown works fine but I need to output Text for exaple...
If 1 day is show then output Day if more days then Days, the same with hours, minutes and seconds..
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
function updateClock() {
const t = getTimeRemaining(endtime);
document.querySelector('.days').innerHTML = t.days;
document.querySelector('.hours').innerHTML = t.hours;
document.querySelector('.mins').innerHTML = t.minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2);
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
const countdown = "November 18 2022 19:00:00";
initializeClock("#codo", countdown);
1 Days 2 Hours 1 Minute 30 Seconds
I tried eg:
if(days > 1) { var day = 'Days'; } else { var day = 'Day'; }
But where exactly do I have to install it to output the text, I've tried a few things but non-stop initialize error given.
updateClock sets the output, specifically the 4 lines begining with document.querySelector. They set the content of 4 elements in your HTML.
function updateClock() {
const t = getTimeRemaining(endtime);
/* determine plural/singular word */
const days = t.days>1?" days":" day"
const hours = t.hours>1?" hours":" hour"
const minutes = t.minutes>1?" minutes":" minute"
const seconds = t.seconds>1?" seconds":" second"
/* append word to value */
document.querySelector('.days').innerHTML = t.days + days;
document.querySelector('.hours').innerHTML = t.hours + hours;
document.querySelector('.mins').innerHTML = t.minutes + minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2) + seconds;
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
innerHTML as the name suggests, sets the HTML inside the element. (as a string).
element.innerHTML = `Hello <div class="smallWord">World</div>`
I have a count down that whenever it is running, it blocks a form on the page and does not let the form be sent. Why is this happening ? I'll leave my javascript code below. Whenever I activate and try to click the form submit button from any page, the button just does nothing, I debugged it and I got to this part of the code, I don't understand how this javascript code can solve my forms.
<script type="text/javascript">// <![CDATA[
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = jQuery('.' + id);
for (let index = 0; index < endtime.length; index++) {
var element = endtime[index];
atualDate = new Date();
deadlineDate = new Date(element);
if (atualDate.getTime() < deadlineDate.getTime()) {
break;
}
}
function updateClock() {
var t = getTimeRemaining(element);
console.log(clock);
if (t.total > 0) {
jQuery(clock).find('.days').html(t.days);
jQuery(clock).find('.hours').html(('0' + t.hours).slice(-2));
jQuery(clock).find('.minutes').html(('0' + t.minutes).slice(-2));
jQuery(clock).find('.seconds').html(('0' + t.seconds).slice(-2));
} else {
jQuery(clock).find('.days').html('0');
jQuery(clock).find('.hours').html('00');
jQuery(clock).find('.minutes').html('00');
jQuery(clock).find('.seconds').html('00');
}
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
const deadline = ["2022-09-14 09:02:00", "2022-09-14 10:36:00", "2022-11-14 10:37:00"];
initializeClock('countdown', deadline);
// ]]></script>
I want to create a countdown to a set date and time. When the deadline arrives the timer will reset to 24 hours. Every day it will count down to 14:15.
This is the code below. Thanks in advance.
(function() {
var deadline = '2021/12/30 14:15';
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date()),
seconds = Math.floor((t / 1000) % 60),
minutes = Math.floor((t / 1000 / 60) % 60),
hours = Math.floor((t / (1000 * 60 * 60)) % 24),
days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function clock(id, endtime) {
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes');
var timeinterval = setInterval(function() {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
deadline = "een datum"
clearInterval(timeinterval);
} else {
hours.innerHTML = pad(time.hours, 2);
minutes.innerHTML = pad(time.minutes, 2);
}
}, 1000);
}
clock('js-clock-header', deadline);
function clocks(id, endtime) {
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes');
var timeinterval = setInterval(function() {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
clearInterval(timeinterval);
} else {
hours.innerHTML = pad(time.hours, 2);
minutes.innerHTML = pad(time.minutes, 2);
}
}, 1000);
}
clocks('js-clock', deadline);
})();
<span id="js-clock-header-hours"></span>:<span id="js-clock-header-minutes"></span><br />
<span id="js-clock-hours"></span>:<span id="js-clock-minutes"></span>
I am using this timer on each of my product pages: http://www.screencast.com/t/hsmzVOLBUJ
and example of product page URL:
https://www.tresor-ethnique.com/collections/celtique/products/pendentif-chene-millenaire
It starts at 12hrs 4mn 26s and then decreases.
I would like it to be set with a cookie so that when the user navigates between different product pages, it keeps decreasing from the value of other pages ; and also if the user comes back in 12hrs, it displays 0hrs 4mn 26s.
So I am a bit unfamiliar with the integration of cookie in javascript, this would appear in the end of my code there:
document.cookie = 'myClock='
So far, the timer resets after each refresh
Do you have any idea to prevent that?
This would be a great help, thank you very much :)
<div id="clockdiv">
<span class="days"></span><div class="smalltext">jours</div>
<span class="hours"></span><div class="smalltext">hrs</div>
<span class="minutes"></span><div class="smalltext">mins</div>
<span class="seconds"></span><div class="smalltext">secs</div>
</div>
<script type="text/javascript">
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var currentTime = Date.parse(new Date());
if(document.cookie && document.cookie.match('myClock')){
var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
}
else{
var timeInHours = 12;
var timeInMinutes = 4;
var timeInSeconds = 26;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInHours*60*60*1000 + timeInMinutes*60*1000 + timeInSeconds*1000);
document.cookie = 'myClock=' + deadline + '; path=/; domain= .https://www.tresor-ethnique.com/';
initializeClock('clockdiv', deadline);
}
</script>
I'm trying to create a countdown counter that should countdown for 24 hours, displaying the days, the hours, the minutes and the seconds. The question is that I want to make it somehow save the progress. For example, I put the countdown to start from now till tomorrow the same time (24 hours) and when a user comes in my site after 2 hours the counter should start from 22 hours for that user and if the user closes the site and then comes back after 2 hours the counter should start from 20 hours for that user. I hope it's clear enough. I found that if that is possible it could be done using cookies, but I'm not sure how it should be done... If anyone could help it will be great! :3
Here is my code so far:
HTML:
<div id="clockdiv">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>
JavaScript
// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
// get deadline value from cookie
var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
}
// otherwise, set a deadline 10 minutes from now and
// save it in a cookie with that name
else{
// create deadline 10 minutes from now
var timeInMinutes = 1380;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);
// store deadline in cookie for future reference
document.cookie = 'myClock=' + deadline + '; path=/; domain=.optic2n.com';
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
initializeClock('clockdiv', deadline);
Thank you in advance for the help! :3
Best regards,
Tsvetko Krastev
It is possible I have missed something, but your code seems very complex for something so simple. Here is what I came up with:
HTML:
<div id="clockdiv">
<span id="d" class="days"></span>days
<span id="h" class="hours"></span>hrs
<span id="m" class="minutes"></span>mins
<span id="s" class="seconds"></span>secs
</div>
Javascript:
var deadline = localStorage.getItem('dl') ? parseInt(localStorage.getItem('dl')) : (Date.now() + 86400000);
var delay = null;
// Good spot to do checks for 24hrs has passed already here
localStorage.setItem('dl',deadline);
function render() {
if (delay) {
clearTimeout(delay);
delay = null;
}
var diff = (deadline - Date.now()) / 1000;
document.getElementById('d').innerHTML = Math.floor(diff / 86400);
document.getElementById('h').innerHTML = Math.floor(diff / 3600);
document.getElementById('m').innerHTML = Math.floor((diff / 60) % 60);
document.getElementById('s').innerHTML = Math.floor(diff % 60);
delay = setTimeout(render,1000);
}
render();
NOTE: There are no checks for what to do after 24 hours.