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

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

Related

How can I round time to hours and minutes instead of hours, minutes and seconds?

My function returns the time like this 10:43:22 for example. How can I round the time to the closest minute so 10:43:22 becomes 10:43 and 10:43:44 becomes 10:44.
function time (){
let date = new Date()
let time = date.toLocaleTimeString("it-IT");
}
I would get the milliseconds of that date and then round that value to minutes (1 minute = 60,000 milliseconds).
function createRoundedDate(date) {
var ts = date.getTime();
ts = Math.round(ts / 60000) * 60000;
return new Date(ts);
}
console.log(createRoundedDate(new Date()))
we can use the below code to create the new Date by removing the seconds part
var d = new Date()
var d1 = new Date(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes())
console.log(d1.toLocaleTimeString('it-IT'))
This should do it, and handle going over hours etc. (60,000 ticks is 1 min)
function time(){
let date = new Date()
let dateMins = new Date(date.getYear(),date.getMonth(),date.getDay(),date.getHours(),date.getMinutes())
let roundedDate = new Date(dateMins.getTime() + date.getSeconds() > 30 ? 60000 : 0 )
let time = roundedDate.toLocaleTimeString("it-IT");
}

Jquery timer with UTC offset

function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getUTCHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if (cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if (cur_mins < 10) {
cur_mins = '0' + cur_mins;
Here’s the code for a simple 24 hour countdown timer that resets again after each 24 hours but when I add, say, 11- hours in the compute time remaining section it occasionally throws a negative time (in hours) at me depending on the current UTC time. I’d just like the 24 hour period to start from a different time /time zone. All help greatly appreciated
You might be looking at this backwards :-) Why don't you create a Date object for midnight, then subtract current time from it. This example works for the local timezone, but you could easily adapt it for UTC, or another timezone.
// We're going to use Vue to update the page each time our counter changes.
// You could also do this old style, updating the DOM directly.
// vueStore is just a global variable that will contain the current time,
// and the function to periodically update it.
var vueStore = {
now: new Date(),
countdown(){
vueStore.now = new Date();
window.setTimeout(() => {this.countdown(); }, 1000);
}
};
vueStore.countdown();
var vm = new Vue({
el: "#vueRoot",
data: { vueStore: vueStore },
computed: {
timeTilMidnight() {
var midnightTonight = new Date(this.vueStore.now.getYear(), this.vueStore.now.getMonth(), this.vueStore.now.getDay() + 1);
var timeToMidnight = midnightTonight.getTime() - this.vueStore.now.getTime();
return new Date(timeToMidnight).toLocaleTimeString([], {
timeZone: "UTC"
});
}
}
});
<script src="https://unpkg.com/vue#2.5.17/dist/vue.js"></script>
<div id="vueRoot">
<h1>{{timeTilMidnight}}</h1>
</div>

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>

looping function every second

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/

Categories