Call a javascript function at a specific time of day - javascript

for example i want to call a js function at 10.00.00.00 am
how can i do?
<script type="text/javascript">
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 30, 0, 0) - now;
setTimeout(function{openAPage(), setInterval(openAPage, 60*1000)}, millisTill10)
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
document.write("<br>button pressed#</br>")
document.write(new Date(startTime));
document.write("<br>page loaded#</br>")
document.write(new Date(endTime));
document.write("<br>time taken</br>")
document.write(timeTaken);
myWin.close()
}
</script>
i expect from this code at 00.30 it will open google and then every 1 minute later it will do it again? whats wrong with that code?

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

My solution for running a script at a specific time, btw no error checking for negative timeout.
//year, month 0-11, date, hour, min (can add ,sec,msec)
var eta_ms = new Date(2015, 0, 21, 17, 0).getTime() - Date.now();
var timeout = setTimeout(function(){}, eta_ms);

Assuming the code is located on a web page that will be loaded before 10:00 and will still be viewed at 10:00, you can use setTimeout() to set up a timed event. the function takes some JS statement to execute, and the number of milliseconds before it should execute. You can find this second part pretty easily with the built-in date functions.

Try this
$(document).ready(function() {
setTimeToTrigger();
});
function setTimeToTrigger(){
var dt = new Date();
var hour = dt.getHours();
var minute = dt.getMinutes() ;
var seconds = dt.getSeconds();
if(hour<10){
nexthour=9;
}else if(hour<22){
nexthour=21;
}else{
nexthour=23-hour+9;
}
delaytime=(nexthour-hour)*60*60+(59-minute)*60+(59-seconds);
alert('will be triggered in :'+ delaytime + ' seconds');
setTimeout( function() {
alert("The time is 10:00");
}, delaytime*1000);
}
<html>
<head>
<title>alert at specific time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>Alert at at 10:00 AM and 10:PM</h3>
</body>
</html>

Related

Move a div to another div on a specific time frame

Like on 7 am in the morning the code runs and moves a div to another div
here is my code
jQuery(document).ready(function(){
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html(" ");
});
The code will run when you load the page.
If you want to move something, then you need to check every time you load the page what the time is, and then try to open in x milliseconds OR you need to run an interval and see if the time has been reached.
Method one:
$(function(){
var now = new Date(); // or new Date(time in milliseconds from server)
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(),7,0,0,0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate()+1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
var tId = setTimeout(function() {
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
},diff);
});
Method 2
$(function() {
var tId = setInterval(function() {
var now = new Date();
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 7, 0, 0, 0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate() + 1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
if (diff <= 60000) { // within a minute - you could use Math.abs here
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
}
}, 1000); // 30000: test every 30 seconds
});
Set an interval on page load, which will run on every 1 second. and will check the time. If the time is 07:00 am to 09:59 am then it will remove content from a div and paste into another div.
You can check the working fiddle here - Example
To test it, uncomment the line var today = new Date('01/01/2011 07:00:00'); and comment the next line var today = new Date();
var interval = setInterval(myfunction, 1000);
function myfunction() {
//var today = new Date('01/01/2011 07:00:00');
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes();
//console.log(time);
if (time >= '7:0' && time <= '9:30') {
clearInterval(interval);
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html("");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="day">
content of day div
</div>
<div id="day-dest">
fghgjgh
</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);

Call javascript function at specific times of day

So I have the following code and it works very well for one specific time of day eg: 4pm but I would like to also call this specific function on other times within the day.
I may need to also call it at 7am, or 11am, or 7am, 11am, and 4pm. any help would be great.
setInterval(function interval(){
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 0, 0, 0) - now;
if (time < 0) {
time += 86400000;
}
setTimeout(function () {
my_function();
timeout();
}, time);
return interval;
}(),1800000);
How about using this: checks every hour if the current hour matches your array of wanted hours and if it does, executes a custom function
function checkHour(){
var d = new Date();
var hours_to_run=[1,13,17,23];
if(hours_to_run.indexOf(d.getHours()) != -1){
runCustomFunction();
}
setTimeout(checkHour, getMilisecondsLeft());
}
function runCustomFunction(){
console.log('yay its 1am, 1pm, 5pm or 11pm!!');
}
function getMilisecondsLeft(){
var d = new Date();
return 1000*60*60 - (d.getMinutes()*1000*60 + d.getSeconds()*1000+ d.getMilliseconds());
}
setTimeout(checkHour, getMilisecondsLeft());
How about this. It schedules a timeout for each of the required hours, and then reschedules any time one of these timeouts elapses:
function schedule(time) {
var now = new Date(),
next = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
time, 0, 0, 0),
diff = next - now;
if (diff < 0) {
diff += 86400000;
}
setTimeout(function () {
my_function();
schedule(time);
}, diff);
}
var times = [7, 11, 16];
times.forEach(schedule);

Countdown.js tweaking

I'm using countdown.js: http://blog.smalldo.gs/2013/12/create-simple-countdown/
I have no experience with JavaScript, and I need the countdown to be set to a week from now, 7 days, so February 24, 2014.
How would I go about changing this?
Here is what I have in my html:
<head>
<script src="/js/countdown.js"></script>
</head>
<h1 id="countdown-holder"></h1>
<script>
var clock = document.getElementById("countdown-holder")
, targetDate = new Date(2050, 00, 01); // Jan 1, 2050;
clock.innerHTML = countdown(targetDate).toString();
setInterval(function(){
clock.innerHTML = countdown(targetDate).toString();
}, 1000);
</script>
Just change targetDate = new Date(2050, 00, 01);
to targetDate = new Date(2014, 01, 24);
The date constructor takes year, month-1, day.
This is for a fixed date (such as Feb 24 2014), not a relative date (such as "one week from today").
var newDate = new Date();
var numberOfDaysToAdd = 7;
newDate.setDate(newDate.getDate() + numberOfDaysToAdd);
var clock = document.getElementById("countdown-holder")
, targetDate = newDate;
clock.innerHTML = countdown(targetDate).toString();
setInterval(function(){
clock.innerHTML = countdown(targetDate).toString();
}, 1000);
This will start counter from 7 days. It will add 7 days to todays date.
try something like this, here is also the js fiddle:
http://jsfiddle.net/rnewsome/D3tPR/
Requires an html element on the page like so:
<div id="counter" />
var StartTime = new Date();
var counter = document.getElementById("counter");
var timeout = null;
function GetCount() {
var timeToExpire = new Date(StartTime);
timeToExpire.setDate(timeToExpire.getDate() + 7);
var ms = timeToExpire.getTime() - new Date().getTime();
console.log(ms + "ms", (ms/1000) + "s");
return ms;
};
function UpdateUI() {
var timeRemaining = parseInt(GetCount() / 1000);
counter.innerHTML = timeRemaining + " seconds";
if(timeRemaining > 0) {
timeout = setTimeout(UpdateUI , 1000); // Update Counter every second
}
}
// Init
UpdateUI();

checking if a current time falls in a particular interval in javascript

EDIT: Please take care to introduce UTC timing in your answer. Since doing things on client side will lead to different time zones.
In javascript, i can get the current time, hour and minute as follows:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
Now i have to perform a task only if the current time false in an interval with a fixed time.
Say there is a fixed time 10:30 AM. Users can perform a certain task iff the current time, is 4 hours behind the current time or 1 hour ahead of the fixed time.
meaning users can perform the task from 6:30 AM to 11:30 AM.
I tried getting the current hours and doing
start = fixed_time - 4;
end = fixed_time + 1;
if currentHour< end or currentHour > start{
do some stuff;
}
But this ignores the minutes, how to take care of that?
Otherwise, how could i figure if the current time lies between 6:30 AM and 11:30 AM?
var currentTime = new Date();
var startTime = new Date(2012, 3, 8, 6, 30, 0, 0); //6:30am today
var endTime = new Date(2012, 3, 8, 11, 30, 0, 0); //11:30am today
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
If you need it to be more dynamic you can
var currentTime = new Date();
var startTime = new Date();
startTime.setHours(6);
startTime.setMinutes(30);
var endTime = new Date();
endTime.setHours(11);
endTime.setMinutes(30);
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
You can use getTime() method which returns the number of milliseconds since midnight Jan 1, 1970:
currentTime = (new Date()).getTime();
Then all you need is to calculate the difference between your fixed time and current time in milliseconds. 4 hours equals to 14,400,000 (4*60*60*1000) milliseconds.
You can compare dates to one another. So, using the current date and time you can compare that to dates with a fixed time set. Something like:
var now = new Date
,lower = new Date
,upper = new Date;
//determine limits
lower.setHours(6);
lower.setMinutes(30);
upper.setMinutes(30);
upper.setHours(11);
//tests
now = new Date('2012/04/08 22:00');
console.log(now >= lower && now <= upper); //=> false
now = new Date('2012/04/08 07:00');
console.log(now >= lower && now <= upper); //=> true
var startTime = '01 AM'; // or var startTime = '01:00 AM';
var endTime = '09 AM'; // or var startTime = '09:00 AM';
var now = new Date();
if(now < convert_time(endTime) && now > convert_time(startTime)){
alert("With in a range");
}else{
alert("Out of range");
}
function convert_actual_time(time) {
if(time.indexOf(" ") != -1){
split1 = time.split(" ");
splitTime = split1[0];
splitZone = split1[1];
}
if(splitTime.indexOf(":") != -1){
split2 = splitTime.split(":");
setHours = split2[0];
setMins = split2[1];
}else{
setHours = splitTime;
setMins = "00";
}
if(splitZone.toLowerCase() == "pm"){
setHours = parseInt(setHours)+12;
}
date = new Date();
date.setHours(setHours);
date.setMinutes(setMins);
return date;
}
Try with this code

Categories