looping function every second - javascript

Im making a countdown timer and I want the time to refresh every second. Im using setInterval but it only seems to be running once instead of every second. What is wrong with my code?
var countDown = setInterval(function(){
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);
demo: http://jsfiddle.net/EnigmaMaster/pyRR8/14/

You need to recalculate the time left within the interval, otherwise you'll continue to set it to the same value.

Your code was not updating the currentDate variable. I updated the code on jsFiddle and paste it here:
var endDay = new Date('May 24, 2012 11:30:00');
var countDown = setInterval(function(){
var currentDate = new Date();
var daysdecimal = (endDay - currentDate)/(1000*60*60*24);
var daysLeft = Math.floor(daysdecimal);
var hoursdecimal = (daysdecimal - Math.floor(daysdecimal))*24;
var hoursLeft = Math.floor(hoursdecimal);
var minLeft = 60 - currentDate.getMinutes();
var secLeft = 60 - currentDate.getSeconds();
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);

want to look like this? I have updated your Jsfiddle
See here : http://jsfiddle.net/pyRR8/23/

Related

How to find time difference in seconds using moment.js

How can I find time difference in seconds between two different timezones.
I want to use moment for this -
My start time is something like- 2022-09-04T07:29:39Z[UTC] and end time will be the current time in my frontend.
My code =
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss")); //NAN
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
console.log("Time Difference =",s);
I need help in this, currently I am getting ms as NAN how can I correct it!
This type of calculation can easily be done with Vanilla JavaScript:
const now = new Date().getTime(),
then = new Date("2022-03-04T07:29:39Z"),
tsec= Math.round((now-then)/1000),
sec=tsec%60, tmin=(tsec-sec)/60,
min=tmin%60, th=(tmin-min)/60,
h=th%24, d=(th-h)/24;
console.log(`Time Difference = ${d}d ${h}h ${min}m ${sec}s`);
d.format is not a function exposed by momentjs instead of that you should write like below
var now = new Date().getTime();
var then = "2022-03-04T07:29:39Z[UTC]";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = moment(d).format('hh:mm:ss')
console.log("Time Difference =",s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How do I re-instantiate the date object in a variable?

So i have the below. It may not have the correct syntax because i had to remove a few lines but it works. It's just that I have to refresh the page for the counter to update.
Is there a way that the counter updates itself every one minute. The setInterval doesn't work because the loginDown new Date hasn't been instantiated again (the page hasn't refreshed) is there a way for loginDown to instantiate again every minute?
function counter(hours, minutesLeft){
alert(hours + minutesLeft);
}
$(document).ready(function() {
var now = new Date();
var loginDown = new Date(now.getFullYear(), now.getMonth(),now.getDate(), 15,10,0,0) - now;
var date = new Date(loginDown);
var hours = date.getHours();
var minutesLeft = date.getMinutes();
counter(hours,minutesLeft);
setInterval(counter(hours,minutesLeft), 60000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The setInterval doesn't work because the loginDown new Date hasn't
been instantiated again (the page hasn't refreshed) is there a way for
loginDown to instantiate again every minute?
No, you are simply not passing the function reference as a parameter.
Make it
setInterval(function(){counter(hours,minutesLeft)}, 60000);
Also, instantiate your date in the counter method itself.
function counter(){
var now = new Date();
var date = new Date(now.getFullYear(), now.getMonth(),now.getDate(), 15,10,0,0) - now;
var hours = date.getHours();
var minutesLeft = date.getMinutes();
alert(hours + minutesLeft);
}
$document.ready({
setInterval(counter, 60000);
});

Automatically load new HTML page at given time

I would like my homepage to change each day at a specific time (1pm).
The page has a 24hr countdown timer and when it reaches zero, I would like a new page to load and the timer starts again.
I understand how to make a page refresh after a particular time
<script>
setTimeout(function(){
window.location='Page2.html';
}, 5000);
</script>
But not how to make this happen at a particular time of the day (1pm).
You can try using a getting the current time on page load/refresh. Then calc the milliseconds until 1pm. And use that to set your setTimeout. I suggest using a library like moment to do time calculations.
Load moments in your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
In JS:
// time right now
var now = moment.now();
// set refresh hour to 1pm
var nextRefresh = moment.now().hour(13).minute(0).second(0).millisecond(0);
// check if is or after 1pm
if (now.hour >= 13) {
nextRefresh.add(1, 'days'); // add 1 day
}
setTimeout(function() {
console.log('next 1pm');
}, nextRefresh.diff(now));
And #Stoycho Trenchev is right. You will probably want to call setInterval with 86400000 ms in the setTimeout. This way, your page will refresh everyday afterwards.
You need setInterval not setTimeout and you need to calculate 24h in milliseconds :)
Here you go just a fyi JavaScript uses the browsers time so just because it's 1pm where you are it won't be 1pm where the user is.
var intervalId = window.setInterval(checkTime, 500);
function checkTime() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(h == 13 && m == 0 && s == 0) return window.location='Page2.html';
}
Ah. Something like?
<script>
function getTime() {
var date = new Date()
var time = date.getTime();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var time = {'hours': hours, 'minutes': minutes, 'seconds': seconds};
}
setInterval(function() {
var time = getTime();
if (time.hours === 13 && time.minutes === 0) {
window.location = 'Page2.html';
}
}, 500);
</script>
You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

Javascript .getTime() inconsistent results between between windows

I need to show a countdown timer. I get time from my server and should count down to zero, based on the following:
var now = new Date().getTime();
var timeRemaining = endTime - now;
.... I start the contdown timer with timeRemining
What happens is when I start the timer in two different tabs, the timer is off by about 2 seconds.
If I do this in one tab and another private window/tab, the timer can be different much much more.
Is there something I can do about this?
var end = new Date('2015-10-27T13:00:00');
var endTime = end.getTime();
var div = document.getElementById('time');
setInterval(function() {
var now = new Date().getTime();
var timeRemaining = endTime - now;
var seconds = timeRemaining / 1000;
div.innerText = Math.floor(seconds);
}, 1000);
<div id="time"></div>

jQuery backword Countdown from Initial HTML Value

I have a initial timer value. How can i make it so that it start counting down to 0?
I want the output to get displayed in another element
<span id="time">03:30:00</span>
<span id="output"></span>
<script type="text/javascript">
jQuery(function($){
var val = $("#time").html();
var output = "";
// count down
$("#output").html(output)
});
</script>
<script type="text/javascript">
$(function(){
var val = $("#time").html().trim();
console.log(val);
val = val.split(":");
var hr = parseInt(val[0].trim());
var mn = parseInt(val[1].trim());
var sc = parseInt(val[2].trim());
console.log(val);
var timer = setInterval(function(){
if(hr==0 && mn==0 && sc==0){
clearInterval(timer);
return;
}
if(sc==0){
sc=60;
mn--;
}
if(mn==0 && sc==0){
mn=60;
hr--;
}
sc--;
$("#output").html(hr+":"+mn+":"+sc);
},10);
});
</script>
This is not the correct answer but rather a best practise
You should use the new time element instead
<time datetime="2014-08-29T20:00:00.000Z">3 minutes left</time>
where datetime is the ISO date format for when the correct moment occured in the future
then inside of the element you would present the text how every you want to display it
By doing so you eliminate the slow bandwidth/DOM parsing & javascript compilation to when its start to count down.
When it has begun you should calculate how many hours/minutes/second there is left until that point in the feuter in every digest.
Then you are safe from the incorrect setTimeout/setInterval that doesn't always wait the exact same time, especially when the tab is idle (in the background)
where setTimeout(fn, 1000) could take 4 seconds if it where in the background.
Here is a example.
How you get the date and display it in the DOM is up to you
var finishDate = new Date(Date.now()+10000); // get point in future somehow
var tick = function() {
var now = new Date()
var difference = finishDate - now;
var hours = Math.floor(difference / 36e5),
minutes = Math.floor(difference % 36e5 / 60000),
seconds = Math.floor(difference % 60000 / 1000);
console.log(hours, minutes, seconds);
setTimeout(tick, now.getUTCMilliseconds())
}
tick() // Start the digest

Categories