How can i make something happen in a time range? - javascript

I want a box to popup at 14:00. Later i want it to disappear at 16:00. How can i do this? I am using Android Studio. I want it to be something like this:
if (Calendar.HOUR_OF_DAY > 14) {
Log.d("TIME", "Time Works!");
}

I'm unsure about Android Studio, but for JavaScript alone, you can use the setTimeout() function to invoke some task every X amount of time. Set this up to check the current time every once in a while, and if it's more than 14:00 and less than 16:00, make sure your popup is shown, otherwise close it...
setTimeout(handlePopupVisibility, 60000);
function handlePopupVisibility() {
var now = new Date();
var startTime = dateObj('2:00 PM');
var endTime = dateObj('4:00 PM');
if (now < dateEnd && now > startTime) {
// inside the range, show your element
// (assumes jQuery)
$("#popupID").show();
} else {
// outside the range, hide your element
// (assumes jQuery)
$("#popupID").hide();
}
}
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
(stolen from answer here: How to check if current time falls within a specific range considering also minutes )

Related

Formatting time from seconds to HH:MM:SS in a countdown

I am having this simple countdown:
function offer_countdown_timer(countdown_start, countdown_time, update, complete) {
var start = new Date(countdown_start).getTime();
var interval = setInterval(function() {
var now = countdown_time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
} else {
update(Math.floor(now/1000));
}
},100); // the smaller this number, the more accurate the timer will be
}
and here I call it:
<script>
offer_countdown_timer(
'<%= s.created_at%>',
3600000, // 1 hour in milliseconds
function(timeleft) { // called every step to update the visible countdown
var txt = timeleft+' seconds';
$('#tender_countdown_<%= s.id %>').html(txt);
//$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
},
function() {
$('#product_<%= s.id %>').html('Offer has expired!');
}
);
</script>
Output of this is:
773 seconds
(and it's counting down)
I'd like to see something like this (HH:ss:mm):
00:12:53
(and counting it down).
I tried this to use this (with using the Moment.js lib - https://momentjs.com/docs/):
$('#tender_countdown_<%= s.id %>').html(moment(txt).format('HH:mm:ss'));
But in this case, the output is this:
01:00:00
The time information is wrong, and it's not counting down. Why is that? How do I properly format the countdowning time?
Thank you
The number of seconds is an abstract duration of time, rather than a date representing a specific moment in time. Moment's constructor expects you to give it a date string.
Moment has a Duration object which can parse your data. It doesn't have nice formatting functions yet, but you can construct the desired output easily enough:
var txt = 773;
var m = moment.duration(txt, "s");
var output = m.hours() + ":" + m.minutes() + ":" + m.seconds();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
See https://momentjs.com/docs/#/durations/ for more details.

How to check condition on time

Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}

In JavaScript, how can I have a function run at a specific time?

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.
I am trying to now get a window.print() to run every day at 8 AM.
How could I do this?
JavaScript is not the tool for this. If you want something to run at a specific time every day, you're almost certainly looking for something that runs locally, like python or applescript.
However, let's consider for a moment that JavaScript is your only option. There are a few ways that you could do this, but I'll give you the simplest.
First, you'll have to to create a new Date() and set a checking interval to see whether the hour is 8 (for 8 AM).
This will check every minute (60000 milliseconds) to see if it is eight o'clock:
window.setInterval(function(){ // Set interval for checking
var date = new Date(); // Create a Date object to find out what time it is
if(date.getHours() === 8 && date.getMinutes() === 0){ // Check the time
// Do stuff
}
}, 60000); // Repeat every 60000 milliseconds (1 minute)
It won't execute at exactly 8 o'clock (unless you start running this right on the minute) because it is checking once per minute. You could decrease the interval as much as you'd like to increase the accuracy of the check, but this is overkill as it is: it will check every minute of every hour of every day to see whether it is 8 o'clock.
The intensity of the checking is due to the nature of JavaScript: there are much better languages and frameworks for this sort of thing. Because JavaScript runs on webpages as you load them, it is not meant to handle long-lasting, extended tasks.
Also realize that this requires the webpage that it is being executed on to be open. That is, you can't have a scheduled action occur every day at 8 AM if the page isn't open doing the counting and checking every minute.
You say that you are already refreshing the page every five seconds: if that's true, you don't need the timer at all. Just check every time you refresh the page:
var date = new Date(); // Create Date object for a reference point
if(date.getHours() === 8 && date.getMinutes() === 0 && date.getSeconds() < 10){ // Check the time like above
// Do stuff
}
With this, you also have to check the seconds because you're refreshing every five seconds, so you would get duplicate tasks.
With that said, you might want to do something like this or write an Automator workflow for scheduled tasks on OS X.
If you need something more platform-agnostic, I'd seriously consider taking a look at Python or Bash.
As an update, JavaScript for Automation was introduced with OS X Yosemite, and it seems to offer a viable way to use JavaScript for this sort of thing (although obviously you're not using it in the same context; Apple is just giving you an interface for using another scripting language locally).
If you're on OS X and really want to use JavaScript, I think this is the way to go.
The release notes linked to above appear to be the only existing documentation as of this writing (which is ~2 months after Yosemite's release to the public), but they're worth a read. You can also take a look at the javascript-automation tag for some examples.
I've also found the JXA Cookbook extremely helpful.
You might have to tweak this approach a bit to adjust for your particular situation, but I'll give a general overview.
Create a blank Application in Automator.
Open Automator.app (it should be in your Applications directory) and create a new document.
From the dialog, choose "Application."
Add a JavaScript action.
The next step is to actually add the JavaScript that will be executed. To do that, start by adding a "Run JavaScript" action from the sidebar to the workflow.
Write the JavaScript.
This is where you'll have to know what you want to do before proceeding. From what you've provided, I'm assuming you want to execute window.print() on a page loaded in Safari. You can do that (or, more generally, execute arbitrary JS in a Safari tab) with this:
var safari = Application('Safari');
safari.doJavaScript('window.print();', { in: safari.windows[0].currentTab });
You might have to adjust which of the windows you're accessing depending on your setup.
Save the Application.
Save (File -> Save or ⌘+S) the file as an Application in a location you can find (or iCloud).
Schedule it to run.
Open Calendar (or iCal).
Create a new event and give it an identifiable name; then, set the time to your desired run time (8:00 AM in this case).
Set the event to repeat daily (or weekly, monthly, etc. – however often you'd like it to run).
Set the alert (or alarm, depending on your version) to custom.
Choose "Open file" and select the Application file that you saved.
Choose "At time of event" for the alert timing option.
That's it! The JavaScript code that you wrote in the Application file will run every time that event is set to run. You should be able to go back to your file in Automator and modify the code if needed.
function every8am (yourcode) {
var now = new Date(),
start,
wait;
if (now.getHours() < 7) {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
} else {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 8, 0, 0, 0);
}
wait = start.getTime() - now.getTime();
if(wait <= 0) { //If missed 8am before going into the setTimeout
console.log('Oops, missed the hour');
every8am(yourcode); //Retry
} else {
setTimeout(function () { //Wait 8am
setInterval(function () {
yourcode();
}, 86400000); //Every day
},wait);
}
}
To use it:
var yourcode = function () {
console.log('This will print evryday at 8am');
};
every8am(yourcode);
Basically, get the timestamp of now, the timestamp of today 8am if run in time, or tomorrow 8am, then set a interval of 24h to run the code everyday. You can easily change the hour it will run by setting the variable start at a different timestamp.
I don t know how it will be useful to do that thought, as other pointed out, you ll need to have the page open all day long to see that happen...
Also, since you are refreshing every 5 seconds:
function at8am (yourcode) {
var now = new Date(),
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
if (now.getTime() >= start.getTime() - 2500 && now.getTime() < start.getTime() + 2500) {
yourcode();
}
}
Run it the same way as every8am, it look if 8am is 2.5second ahead or behind, and run if it does.
I try to give my answer hoping it could help:
function startJobAt(hh, mm, code) {
var interval = 0;
var today = new Date();
var todayHH = today.getHours();
var todayMM = today.getMinutes();
if ((todayHH > hh) || (todayHH == hh && todayMM > mm)) {
var midnight = new Date();
midnight.setHours(24,0,0,0);
interval = midnight.getTime() - today.getTime() +
(hh * 60 * 60 * 1000) + (mm * 60 * 1000);
} else {
interval = (hh - todayHH) * 60 * 60 * 1000 + (mm - todayMM) * 60 * 1000;
}
return setTimeout(code, interval);
}
With the startJobAt you can execute only one the task you wish, but if you need to rerun your task It's up to you to recall startJobAt.
bye
Ps
If you need an automatic print operation, with no dialog box, consider to use http://jsprintsetup.mozdev.org/reference.html plugin for mozilla or other plugin for other bowsers.
I will suggest to do it in Web Worker concept, because it is independent of other scripts and runs without affecting the performance of the page.
Create a web worker (demo_worker.js)
var i = 0;
var date = new Date();
var counter = 10;
var myFunction = function(){
i = i + 1;
clearInterval(interval);
if(date.getHours() === 8 && date.getMinutes() === 0) {
counter = 26280000;
postMessage("hello"+i);
}
interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);
Use the web worker in Ur code as follows.
var w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_worker.js");
w.onmessage = function(event) {
window.print();
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support HTML5 Web Workers";
}
}
}
I think it will help you.
I have written function which
allows expressing delay in seconds, new Date() format and string's new Date format
allows cancelling timer
Here is code:
"use strict"
/**
This function postpones execution until given time.
#delay might be number or string or `Date` object. If number, then it delay expressed in seconds; if string, then it is parsed with new Date() syntax. Example:
scheduleAt(60, function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00", function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00 UTC", function() {console.log("executed"); }
#code function to be executed
#context #optional `this` in function `code` will evaluate to this object; by default it is `window` object; example:
scheduleAt(1, function(console.log(this.a);}, {a: 42})
#return function which can cancel timer. Example:
var cancel=scheduleAt(60, function(console.log("executed.");});
cancel();
will never print to the console.
*/
function scheduleAt(delay, code, context) {
//create this object only once for this function
scheduleAt.conv = scheduleAt.conv || {
'number': function numberInSecsToUnixTs(delay) {
return (new Date().getTime() / 1000) + delay;
},
'string': function dateTimeStrToUnixTs(datetime) {
return new Date(datetime).getTime() / 1000;
},
'object': function dateToUnixTs(date) {
return date.getTime() / 1000;
}
};
var delayInSec = scheduleAt.conv[typeof delay](delay) - (new Date().getTime() / 1000);
if (delayInSec < 0) throw "Cannot execute in past";
if (debug) console.log('executing in', delayInSec, new Date(new Date().getTime() + delayInSec * 1000))
var id = setTimeout(
code,
delayInSec * 1000
);
//preserve as a private function variable setTimeout's id
return (function(id) {
return function() {
clearTimeout(id);
}
})(id);
}
Use this as follows:
scheduleAt(2, function() {
console.log("Hello, this function was delayed 2s.");
});
scheduleAt(
new Date().toString().replace(/:\d{2} /, ':59 '),
function() {
console.log("Hello, this function was executed (almost) at the end of the minute.")
}
);
scheduleAt(new Date(Date.UTC(2014, 9, 31)), function() {
console.log('Saying in UTC time zone, we are just celebrating Helloween!');
})
setInterval(() => {
let t = `${new Date().getHours() > 12 ? new Date().getHours() - 12 : new Date().getHours()}:${new Date().getMinutes().length < 2 ? '0' + new Date().getMinutes() : new Date().getMinutes()}:${new Date().getSeconds().length < 2 ? '0' + new Date().getSeconds() : new Date().getSeconds()} ${new Date().getHours()>12?"pm":"am"}`
console.log(t);
}, 1000);

How to run a function at specific time & date?

How can I run a function at a given time and date?
Example: I have a function that needs to run on the 12th of each month at 10AM.
This page will be running 24/7, if this is important.
Obviously I'd have to compare against the current date, but I'm not sure how to check if the current date and time has been matched.
Shannon
It's not advised to use setInterval because it has non-deterministic behaviour - events can be missed, or fire all at once. Time will fall out of sync, too.
The code below instead uses setTimeout with a one minute period, where each minute the timer is resynchronised so as to fall as closely to the hh:mm:00.000s point as possible.
function surprise(cb) {
(function loop() {
var now = new Date();
if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
cb();
}
now = new Date(); // allow for time passing
var delay = 60000 - (now % 60000); // exact ms to next minute interval
setTimeout(loop, delay);
})();
}
On the page where o want to do the check add this
setInterval(function () {
var date = new Date();
if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
alert("Surprise!!")
}
}, 1000)
FIDDLE
Update- add date.getSeconds == 0 to limit it to fire only one at 10:00:00. Thanks to comments below
You can instantiate two Date objects. One for now and one for the next instance of the event. Now is easy: new Date(). For the next instance you can loop through the options till you find one larger than now. Or do some more sophisticated date time wizardry. Compare the getTime() of the both, and then do a setTimeout for the alert.
EDIT:
Updated since #Alnitak points out that there's a maximum to the timeout, see setTimeout fires immediately if the delay more than 2147483648 milliseconds.
function scheduleMessage() {
var today=new Date()
//compute the date you wish to show the message
var christmas=new Date(today.getFullYear(), 11, 25)
if (today.getMonth()==11 && today.getDate()>25)
christmas.setFullYear(christmas.getFullYear()+1)
var timeout = christmas.getTime()-today.getTime();
if( timeout > 2147483647 ){
window.setTimeout( scheduleMessage(), 2147483647 )
} else {
window.setTimeout(function() {alert('Ho Ho Ho!'); scheduleMessage()}, timeout)
}
}
You can use something like this
var runned = false;
var d = new Date();
if(d.getDate() == 12 && d.getHours() == 10 && !runned){
//Do some magic
runned = true;
}
If you want some with the minute (and not the whole hour you can add d.getMinutes()
maybe use and iframe with meta refresh and workout content server side
<meta http-equiv="refresh" content="{CHANGE_THIS_TO_WHAT_YOU_CALCULATED_AT_SERVER}">
or use javascripts setInterval
var interval = 300000; // run in 5 minutes
window.setInterval("reloadRefresh();", interval);
function reloadRefresh() {
// do whatever
}
and

Trying to get countdown with current time versus the days closing time javascript

http://jsbin.com/ocuceb/6/edit
The above link is where the full code is, I am trying to get a count down timer of how many hours and minutes are left till a business closes.
function countDown() {
var d = new Date();
var hour = d.getHours();
if(hour<10){hour="0"+hour;}
else if(hour>12){hour=hour - 12;}
var minutes = d.getMinutes();
if(minutes<10){minutes="0"+minutes;}
var seconds = d.getSeconds();
if(seconds<10){seconds="0"+seconds;}
var open = weekday[day.getDay()].open.replace(/am/g,'');
var close = weekday[day.getDay()].close.replace(/pm/g,'');
open = parseInt(open,10);
close = parseInt(close,10);
//confused here!
var timeClose = close;
var timeRemaining = Math.floor(d.getHours() - timeClose);
document.write('<br><br>Close At: '+timeClose+"pm<br>Time Remaining:"+timeRemaining);
}
And that is where I am having the trouble, I can get the time of being opened and the time of being closed. Originally I tried this
var timeClose = parseInt(close+':00:00',10);
var difference = Math.floor(d.getDay() - timeClose);
And of course this didn't work, it either said Undefined or NaN I'm not sure how to go about this, the timing is all new to me never needed this though a client asked for this. Where it states the Actual Time, What time they close, and show an image if the time is within the open to close time (basically an Open Neon Sign) and when past closed (a closed Neon Sign)... I figured it would be very simple, though I am having so tricky corners to pass.
JavaScript time does not think in 12-hour format. It thinks in 24-hour format. Change your array of objects to reflect (22 being 10pm):
hours[0]= {open:"8:00:00",close:"22:00:00"};
hours[1]={open:"8:00:00",close:"22:00:00"};
hours[2]={open:"8:00:00",close:"22:00:00"};
hours[3]={open:"8:00:00",close:"22:00:00"};
hours[4]={open:"8:00:00",close:"22:00:00"};
hours[5]={open:"8:00:00",close:"22:00:00"};
hours[6]={open:"8:00:00",close:"22:00:00"};
Also, parsing an int like this could lead to issues:
var timeClose = parseInt(close+':00:00',10);
You should substring everything between the colons to get your desired hours or minutes.
var timeClose = parseInt(open.substring(0,open.indexOf(":")),10);
Also with the way you have it set up, during business hours (or before 10pm), you will always have a negative number because you subtract the current hours from the close time. If it's 8pm and the close time is 10pm, we will have -2 hours remaining? Switch the operands to subtract getHours from time instead:
var timeRemaining = Math.floor(timeClose - d.getHours());
After that, you can probably check timeRemaining for a negative value. If it is negative, that means the business is closed, and you can modify your output message to reflect as such, i.e.
var timeRemaining = Math.floor(timeClose - d.getHours());
if (timeRemaining < 0) {
output = "Sorry we are closed already";
} else {
output = "You have " + timeRemaining + " to come in and shop till you drop";
}
I think a simpler way to do this would be something like this
var now=new Date();
var closing=new Date(now.getFullYear(),now.getMonth(),now.getDate(),21);//Set this to 10:00pm on the present day
var diff=closing-now;//Time difference in milliseconds
if(now.getHours<7){
//It's before opening time
}
else if(diff<0){
//It's after closing time
}
else{
var hours=Math.floor(diff/(1000*60*60));
diff=diff%(1000*60*60);
var mins=Math.floor(diff/(1000*60));
diff=diff%(1000*60);
var secs=Math.floor(diff/(1000));
}
Here is a reference on the time object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Categories