I'm trying to compare to 2 dates by hour/minutes/seconds, in order to make a script to resume a script when closed. If current time is pass closed time + interval ( currently set at 30 minutes) should execute and run the script normally, if not wait till difference timeouts to execute.
Current hour/minutes/seconds is not a must but the result should be in ms interval
Example:
interval = (30 * 60 * 1000)
close time = 15:10:53
current time = 15:15:29
close time + interval = 15:40:53
first time I check if `current time` <= `close time + interval`
then calculate `difference`
`difference` = (close time + interval = 15:40:53) - (current time = 15:15:29)
Result should be setTimeout(function(){ alert("Hello"); }, time difference);
The only way I'm thinking of doing this is calculate each difference from Hour,Minutes,Seconds and then finding out the ms for setTimeout
I tried but results were weird, not something that would count as smaller than 30min
var ONE_S = 1000 ;
var timeDiff = Math.abs(closeTime - currentTime);
var diffS = Math.round(timeDiff/ONE_S)
Use Date objects and compare timestamps like so:
var interval = 30 * 60 * 1000;
var closeTime = new Date('Wed Nov 26 2015 10:17:44 GMT-0400 (AST)');
var currentTime = new Date;
var difference = (closeTime - currentTime) + interval;
if(difference < 0) {
console.log('time has expired');
}else{
setTimeout(someFunction, difference);
}
closeTime - currentTime gets the time between timestamps in ms, which will be negative if it's past closing time. We offset closing time by 30 minutes (by adding interval). Then we just have to check if difference < 0 to know if time has expired, and if not we can wait difference milliseconds to trigger someFunction
Related
I am trying to generate time slots with a gap of 15min between each one, like the following :
["15:30", "15:45", "16:00", "16:15"...]
So far, I managed to make it. However, if the current time is 15:25 (just an example) the generated array will start from 15:30 what I need instead (in this case) to generate time slots starting from 16:00 meaning that only the first time slot should be approximately away 30 min from the current time.
Currently, I have the following code :
//Used momentJS library
function getTimeStops(end) {
var roundedUp, startTime, endTime, timeStops;
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
startTime = moment().utc().set({
minute: roundedUp
});
endTime = moment(end, 'HH:mm');
if (endTime.isBefore(startTime)) {
endTime.add(1, 'day');
}
timeStops = [];
while (startTime <= endTime) {
timeStops.push(new moment(startTime).format('HH:mm'));
startTime.add(15, 'minutes');
}
return timeStops;
}
var timeStops = getTimeStops('02:00');
console.log('timeStops ', timeStops);
You're rounding to the nearest half hour here:
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
Round to the nearest hour instead:
roundedUp = Math.ceil(moment().utc().minute() / 60) * 60;
Edit: just realised that the above is wrong and doesn't actually answer your question.
You do need to change your roundedUp value though.
What you need to do is:
Add 30 minutes to the current time
Round it to the closest 15 minute interval
That way - at most - you'll be 7.5 minutes out.
So for step 1, add 30 minutes
var add30mins = moment.utc().add(30, 'minutes')
Now we need to find the closest 15 minute interval.
var roundTo15Mins = Math.round(add30Mins.minute() / 15) * 15;
Then you can plug that into your startTime.
HTH
How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.
I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.
1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?
2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?
This works for me
window.setInterval(function() {
var date = new Date();
if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000;
}
setTimeout(function() {
alert("It's 10am!")
}, millisTill10);
Run a timer for every minute. Show your warning if the current time falls within your allocation. The problem with this code is that it is only accurate up to a minute - not up to the second.
And running this every second is not a good practice.
setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
console.log('Warning!');
}, 1000)
Now we can do more...
We can get the above routine to kick-start a timeout function which is going to be precise in the interval. It will trigger a countdown timer at the correct time and set alarm for another 24 hours.
var starter = setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
setTimeout(timer24(), 1000 * 60 * 24)
}, 1000)
function timer24(){
//Warn every 10 seconds
var countdown = setInterval(function(){
console.log('Warning!');
var d = new Date();
var h = d.getHours();
if (h == 8)
clearInterval(countdown)
}, 10)
setTimeout(timer, 1000 * 60 * 24)
}
setInterval is used to repeat a callback function with a given time, setTimeout is used to run a callback after a specific amount of time. Since you need to create a counter, you can use setInterval here.
Note: If you want to display the users every sconds in 10 minutes, you may use 1000 as the interval timing value. But if you want to show every minutes in the 10 minute duration, then using 60 * 1000 as the interval timing value is better.
setInterval(function(){
var dateNow = new Date();
if(dateNow.getHours() >= 7 &&
dateNow.getMinutes >= 50 &&
dateNow.getHours < 8)
{
// if the alert box isn't displayed yet
// display it first.
// update the display.
}else{
// if the alert box is displayed
// hide it
}
}, 1000); // or 1000 * 60 for minute based display
I need to reload a page's content every 30 minutes (on the hour and 30 minutes past the hour). I'm thinking JavaScript for this, and I've tried the code below, but it goes into an endless loop. I'm not sure how to change it to avoid the loop.
meta tags won't help since they can't execute on a certain minute.
function refreshContent() {
var tDate = new Date();
thisHour = tDate.getHours();
thisMinute = tDate.getMinutes();
thisSecond = tDate.getSeconds();
setTimeout("refreshContent()",60000); // in milliseconds = 1 minute
if ( thisMinute == 0 || thisMinute == 30 ) {
location.reload();
}
}
refreshContent();
You'll need to set only one timer and calculate when is the next time to refresh. That way you can prevent the page from repeatedly reloading itself when the page is loaded exactly at :00 or :30.
var minute = new Date().getMinutes(),
nextRefresh = (30 - (minute % 30)) * 60 * 1000;
setTimeout( function() { location.reload(); }, nextRefresh );
30 - (minute % 30) calculates how many minutes until the next half hour and * 60 * 1000 converts that into milliseconds. After reload is triggered the timer is set to 30 minutes.
You are immediately invoking the refreshContent function when you setup setTimeout. Try setTimeout(refreshContent, 60000);
I am trying to make a small question/answer quiz game using react, and I want to show a timer that counts down every second. Each game will last 10, 15, or 30 minutes at most, so I want to show a timer that updates every second in the bottom of the screen (in big font, of course!), something like 15:00, 14:59, 14:58, and so on until it hits 00:00.
So, given a start time such as 2016-04-25T08:00:00Z, and an end time after adding 15 min of 2016-04-25T08:15:00Z, I want to start the countdown.
My issue is that I am not understanding how to use setIntervals to keep calling my method to find the remaining time.
timeLeft = Math.round(timeLeft/1000) * 1000;
const timer = new Date(timeLeft);
return timer.getUTCMinutes() + ':' + timer.getUTCSeconds();
EDIT: You've edited your question. You will need the time padding, and the method below will be faster than what you are using, but to answer your question about setInterval:
First, define your function to run your timer and decrement each time it's called:
var timeLeft; // this is the time left
var elem; // DOM element where your timer text goes
var interval = null; // the interval pointer will be stored in this variable
function tick() {
timeLeft = Math.round(timeLeft / 1000) * 1000;
const timer = new Date(timeLeft);
var time = timer.getUTCMinutes() + ':' + timer.getUTCSeconds();
elem.innerHTML = time;
timeLeft -= 1000; // decrement one second
if (timeLeft < 0) {
clearInterval(interval);
}
}
interval = setInterval(tick, 1000);
OG Answer:
No, I do not believe there is a built-in way to display time differences.
Let's say you have two date objects:
var start = Date.now();
var end = Date.now() + 15 * 60 * 1000; // 15 minutes
Then you can subtract the two Date objects to get a number of milliseconds between them:
var diff = (end - start) / 1000; // difference in seconds
To get the number of minutes, you take diff and divide it by 60 and floor that result:
var minutes = Math.floor(diff / 60);
To get the number of seconds, you take the modulus to get the remainder after the minutes are removed:
var seconds = diff % 60;
But you want these two padded by zeros, so to do that, you convert to Strings and check if they are two characters long. If not, you prepend a zero:
// assumes num is a whole number
function pad2Digits(num) {
var str = num.toString();
if (str.length === 1) {
str = '0' + str;
}
return str;
}
var time = pad2Digits(minutes) + ':' + pad2Digits(seconds);
Now you have the time in minutes and seconds.
I've a problem when running this script for my JavaScript countdown (using this plugin). What it should do is take the starting time, the current time and the end time and display the remaining time.
If I set these values with normal numbers in epoch time everything works just fine, but my question is: How do I set the current time and the start to be the real current one so that the countdown will be dynamic?
I've found this line: Math.round(new Date().getTime()/1000.0);
But I don't know how to make it work, considering I'm running this script at the bottom of my HTML file, before the </html> tag.
This is the script:
<script>
$('.countdown').final_countdown({
start: '[amount Of Time]',
end: '[amount Of Time]',
now: '[amount Of Time]'
});
</script>
This is how I tried to solve it, but it's not working:
//get the current time in unix timestamp seconds
var seconds = Math.round(new Date().getTime()/1000.0);
var endTime = '1388461320';
$('.countdown').final_countdown({
start: '1362139200',
end: endTime,
now: seconds
});
It sounds like you would like to count down from the current time to some fixed point in the future.
The following example counts down and displays the time remaining from now (whenever now might be) to some random time stamp within the next minute.
function startTimer(futureTimeStamp, display) {
var diff;
(function timer() {
// how many seconds are between now and when the count down should end
diff = (futureTimeStamp - Date.now() / 1000) | 0;
if (diff >= 0) {
display(diff);
setTimeout(timer, 1000);
}
}());
}
// wait for the page to load.
window.onload = function() {
var element = document.querySelector('#time'),
now = Date.now() / 1000,
// some random time within the next minute
futureTimeStamp = Math.floor(now + (Math.random() * 60));
// format the display however you wish.
function display(diff) {
var minutes = (diff / 60) | 0,
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
element.innerHTML = minutes + ":" + seconds;
}
startTimer(futureTimeStamp, display);
};
<span id="time"></span>
Also Math.round(new Date().getTime()/1000.0); will give you the number of seconds since the epoch, however it may be a little disingenuous to round the number. I think you would be better served by taking the floor:
var timestamp = Math.floor(Date.now() / 1000)); is probably a better option.
In addition I am not sure why you need the start time, current time and end time. In order to find the remaining number of second you just need to know when the timer should end and the current time.