Move a div to another div on a specific time frame - javascript

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>

Related

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>

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

Issue on Updating jQuery Timeout

I am trying to make a simple plugin to calculate date and time by this code:
<div id="timer"></div>
<script>
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#timer").append( "<p>"+days+"</p>" );
$("#timer").append( "<p>"+hours+"</p>" );
$("#timer").append( "<p>"+minutes+"</p>" );
$("#timer").append( "<p>"+seconds+"</p>" );
var timer = setTimeout('timeCounter',1000);
};
$("#timer").timeCounter("june 16, 2014 00:01:00");
</script>
the code is working fine but I am having problem on displaying actual count down on numbers! can you please let me know how to fix this?
Thanks
Following displays count down in seconds:
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
// count down logic
setTimeout(function cdtd(){
if (timeDiff > 0){
// reduce one seconds
timeDiff-=1000;
// change this to a more dedicated display per your requirements
$('#timer').html(timeDiff/1000);
// next one second, reference to cdtd
setTimeout(cdtd,1000);}
},1000);
}
See working sample:
http://jsfiddle.net/danyu/X33kv/

Call a javascript function at a specific time of day

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>

Categories