jQuery Timer that refreshes a div element when the minute changes - javascript

I am trying to get a div element to update once one minute goes by from.
I have a function in Javascript that counts down to a specific time in the day, however, I would like to use JQuery so that as the timer is counting down when the minute changes instead of having to refresh the browser it does it without refreshing.
I had a timer that displayed hours, minutes, seconds counting down to a specific setHours() using a setTimout to countdown.
function countdown() {
var now = new Date();
var eventDate = new Date();
var currentTiime = now.getTime();
var eventTime = eventDate.setHours(16, 30, 0);
var remTime = eventTime - currentTiime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
if (now.getHours() >= 9 && currentTiime < eventTime) {
setTimeout(countdown, 1000);
}
At the moment I have a countdown that countdown to 16:30 but displays as:
Hours: minutes: seconds: I would like Hours:xx minutes:xx and when the minute goes down 1 minute it shows in the div without refreshing the page.

Here is a solution that has a bit of JQuery strewn in. Please note that your Javascript solution will work as well. The only difference is that this calls setInterval instead of setTimeout ('setInterval' vs 'setTimeout')
Please try running the code snippet here or on JSFiddle: https://jsfiddle.net/raghav710/tbvmj4px/ . This updates the value without refreshing the page.
EDIT: Added condition to handle when the current time is greater than event time
function get_elapsed_time_string(total_seconds) {
var now = new Date();
var eventDate = new Date();
var currentTime = now.getTime();
var eventTime = eventDate.setHours(17, 00, 0);
var remTime = eventTime - currentTime;
if(remTime <= 0){
clearInterval(interval_id);
$("#hours").html(0);
$("#minutes").html(0);
$("#seconds").html(0);
}
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
$("#hours").html(h);
$("#minutes").html(m);
$("#seconds").html(s);
}
var elapsed_seconds = 0;
var interval_id =
setInterval(function() {
elapsed_seconds = elapsed_seconds + 1;
get_elapsed_time_string(elapsed_seconds);
console.log(interval_id);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hours"></div>
<div id="minutes"></div>
<div id="seconds"></div>

function countdown(){
var now = new Date();
var eventDate = new Date();
var currentTiime = now.getTime();
var eventTime = eventDate.setHours(16, 30, 0);
var remTime = eventTime - currentTiime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? h +" hrs" : h + "hrs";
h = (h <= 1) ? "" : h;
m = (m < 10) ? "0" + m + " mins" : m + " mins ";
if(now.getHours() >= 9 && currentTiime < eventTime){
setTimeout(countdown, 1000);
document.getElementById("timer").textContent = h + " " + m;
}
else if(now.getHours() < 9 || currentTiime >= eventTime){
var t = document.getElementsByClassName("order-day")[0];
t.getElementsByClassName("order-day")[0].textContent = "Order by 4:30pm for same day dispatch";
hideCountdown();
}

Related

How do I stop my countdown timer from executing after it has reached the deadline on refresh of my browser

This is how the JavaScript looks like. I tried searching for solutions but couldn't find. Please I need detailed solutions. Online I kept seeing cookies but I don't know how to use it in this case.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 5, 22);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
var t = setTimeout(countDown, 1000);
if (d == 0 && h == 0 && m == 0 && s == 0) {
clearTimeout(t);
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
}
countDown();
</script>
The trouble with your code is in the date checking logic.
Checking with == will only give you a truthy response if the datetime (or part thereof) is the same as the value you're checking it against.
However, you need to check whether the date is already past. To do this, you need to use a < or <= operator.
Here's an example of what I mean. The info is console.loged instead, you can re-implement the DOM editing you have in your question.
function countDown() {
var now = new Date();
var eventDate = new Date(2020, 4, 22); // 22 May 2020
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h: h;
m = (m < 10) ? "0" + m: m;
s = (s < 10) ? "0" + s: s;
var t = setTimeout(countDown, 1000);
// This if statement only runs exactly on eventDate
if (d == 0 && h == 0 && m == 0 && s == 0) {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
// This if statement will run if we're past or exactly on eventDate
if (remTime <= 0) {
clearTimeout(t);
}
// This console.log shows that the numbers become negative after the date
console.log(remTime, d,h,m,s);
}
countDown();

Cannot set property 'textcontent' of null

for some reason with this I get the error: Cannot set property 'textcontent' of null for this line:
document.getElementById("days").textContent = d;
function countdown() {
var now = new Date();
var eventDate = new Date(2018, 1, 19);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementbyId("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
}
countdown();
<li>
<span class="value">Ends in:
</span>
<p id="days">30</p>
<p id="hours">10</p>
<p id="minutes">5</p>
<p id="seconds">1</p>
</li>
The issue may be that the element may not exist at the time your "countdown" runs... Could you try calling countdown onload of the body / div that contains the set of elements you're querying?
<body onload="countdown()">
The only issue that I see is that your b needs to be uppercase on this line:
document.getElementbyId("minutes").textContent = m;
When fixing that the code works as expected:
function countdown() {
var now = new Date();
var eventDate = new Date(2018, 1, 19);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
}
countdown();
<li>
<span class="value">Ends in:
</span>
<p id="days">30</p>
<p id="hours">10</p>
<p id="minutes">5</p>
<p id="seconds">1</p>
</li>
Make sure that your code is ran after the dom has finished loading.
you can do so like this:
document.addEventListener('DOMContentLoaded', () => countdown());
You have an error: getElementById instead of getElementbyId.
The new code will be:
function countdown() {
var now = new Date();
var eventDate = new Date(2018, 1, 19);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
document.getElementById("days").textContent = d;
document.getElementById("days").innerText = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
}
countdown();
<li>
<span class="value">Ends in:
</span>
<p id="days">30</p>
<p id="hours">10</p>
<p id="minutes">5</p>
<p id="seconds">1</p>
</li>

javascript compare Two Times

Trying to get it to change between 16:30:00 and 17:30:00, to change the text font colour
Tried nested if statements as well
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
if ((h>=16 && m >=30) && (h<=17 && m<=30))
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
try to use setInterval() it's look more clear:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
if((h==16 && m>=30) || (h==17 && m<=30)){
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
};
setInterval(startTime, 500);
The main bug in your logic is looking for minutes where it is both less than and equal to 30 AND greater than and equal to 30. The only way that part evaluates to true is if minutes is 30.
I would normalize the time (so that each combination of hour, minute and second can be represented by a unique number) and use that for comparisons.
function startTime(el) {
var today = new Date();
var hour = today.getHours(),
minute = today.getMinutes(),
second = today.getSeconds();
var normalized_time = normalizeTime(hour, minute, second);
document.getElementById(el).innerHTML
= hour + ":" + padTime(minute) + ":" + padTime(second);
document.getElementById(el).style.color
= normalized_time >= normalizeTime(16, 30, 0)
&& normalized_time <= normalizeTime(17, 30, 0)
? 'red'
: 'black';
}
/*
* Add a 0 to the beginning of the number if one-digit number
*/
function padTime(i) {
return i < 10 ? '0' + i : i;
}
/*
* Converts the time to a normalized version
*/
function normalizeTime(h, m, s) {
return s + (60 * m) + (60 * 60 * h);
}
var t = setInterval(startTime, 500, 'txt');
<span id="txt"></span>
Edit: As per you question you want to take hour and minute into account for comparison, So i have not included the second's part.
The following function get an integer value against time , that later used for the comparison.
function getSeconds(hh,mm,ss)
{
return (Number(hh) * 60 * 60) + (Number(mm) * 60) + Number(ss);
}
Complete code :
function getSeconds(hh,mm,ss)
{
return (Number(hh) * 60 * 60) + (Number(mm) * 60) + Number(ss);
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
var timeNow = getSeconds(h,m,s);
//if ((h>=16 && m >=30) && (h<=17 && m<=30))
if (timeNow >= getSeconds(16,30,0) && timeNow <= getSeconds(17,30,00))
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime();
Updated Fiddle
Previous Response
Try the Fiddle
The problem with your code is you are comparing m with contradictory conditions.
I have concatenated the hour and minutes like following and used that for time comparison
var hrs = Number(h+'.'+m);
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
var hrs = Number(h+'.'+m);
//if ((h>=16 && m >=30) && (h<=17 && m<=30))
if (hrs >= 16.30 && hrs <= 17.30)
{
document.getElementById("txt").style.color = "red";
}
else
{
document.getElementById("txt").style.color = "black";
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime();

JavaScript Countdown Timer to specific time everyday

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);
});

Countdown HH:MM:SS in Jquery

I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}

Categories

Resources