I have a website that I want to be reloaded at a certain time, like 3:35pm, not after a specific interval like 5min. How do I do that?
The following JavaScript snippet will allow you to refresh at a given time:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then you can add a script tag to call the refreshAt() function.
refreshAt(15,35,0); //Will refresh the page at 3:35pm
Note that this code will refresh based on the client local time. If you want it to be at a specific time regardless of the client's timezone, you can replace get*() and set*() (except getTime()) on the time objects with their getUTC*() and setUTC*() equivalent in order to pin it to UTC.
<META HTTP-EQUIV="Refresh" CONTENT="5">
this will force page to reload every 5 seconds. Just calculate the correct interval and add it to content tag
I found this page with a similar question and used it to hack out a more specific answer that may be of use to some. For this project, we wanted to make sure that the page refreshed once a live event of global interest was about to go on, activating the player embed on the user's page (narrow use case, I know -- others might have a better use for it).
One challenge in the above answers was how to deal with time zone conversions, which was more of an issue for us because we wanted to make sure that the page refreshed at a specific day and time. To do this, I grabbed a UTC version of the target date and today's date, converted them to GMT, then set Andrew's timeout function to the difference between the two.
var target = new Date("January 28, 2011 13:25:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
Basically, when the page is accessed, calculate how much time is remaining between the access time and the time you want to reload the page, and use that remaining time in the meta refresh header. Obviously this would need to be done in a CGI script or web application, or possibly with SSI (server-side includes); it won't work if all you have is a static HTML file.
Another alternative would be to use Javascript, but it won't work if the client has Javascript disabled.
This worked better for my purposes.
If you're able to use Jquery and MomentJs, you can do this:
(function () {
var $ = require('jquery');
var moment = require('moment');
function refreshPageAtTime(expiration, countdownElement) {
var now = moment.utc();
console.log('now', now);
var expirationMoment = moment.utc(expiration, 'YYYY-MM-DD kk:mm:ss');
console.log('target', expirationMoment);
var secondsUntilRefresh = expirationMoment.diff(now, 'seconds');//http://momentjs.com/docs/#/displaying/difference/
console.log('diff in seconds', secondsUntilRefresh);
if (secondsUntilRefresh > 1) {
setInterval(function () {
secondsUntilRefresh--;
console.log('seconds remaining', secondsUntilRefresh, 'seconds');
if (secondsUntilRefresh <= 10) {
countdownElement.html(secondsUntilRefresh + '...');
if (secondsUntilRefresh === 0) {
console.warn('Refreshing now at ' + moment.utc());
window.location.reload(true);
}
}
}, 1000 * 1);
}
}
$(document).ready(function () {
var expiration = $('form').attr('data-expiration');
console.log('expiration', expiration);
$('.btn-primary:submit').after('<div id="countdownToRefresh" style="display: inline-block; color: #999; padding: 10px;"></div>');
refreshPageAtTime(expiration, $('#countdownToRefresh'));
});
})();
Basically, there are many javascript codes out there that can refresh the page ever so minutes or something, you can edit them to refresh at hours too. Like this one:
//enter refresh time in "minutes:seconds" Minutes: 0 to Whatever
//Seconds should range from 0 to 59
var limit = "0:30";
if (document.images) {
var parselimit = limit.split(":");
parselimit = parselimit[0] * 60 + parselimit[1] * 1;
}
var beginrefresh = function () {
if (!document.images) return if (parselimit == 1) window.location.reload()
else {
parselimit -= 1;
curmin = Math.floor(parselimit / 60);
cursec = parselimit % 60;
if (curmin != 0) curtime = curmin + " minutes and " + cursec + " seconds left until page refresh!";
else curtime = cursec + " seconds left until page refresh!";
window.status = curtime;
setTimeout("beginrefresh()", 1000);
}
}
window.onload = beginrefresh;
(now just calculate the minutes and seconds you want it to refresh, like for example noon everyday if it were noon now:
var limit = "1440:00";
Now you could use this code except, most of them don't work with server time, And with the information you provided us, we really can't do anything more. Edit your question and tell us if you want it to be timed with the servers time, or something else.
I hope this help,you can set the exact time for refresh
var target = new Date("November 18, 2019 10:00:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
if you using Flask you can set variable synchronized to network time. In the flash app
from datetime import *`
def syncRefresh():`
while (datetime.now().second % 10 !=0):`
continue`
return True`
and #app.route('/', methods =["GET"})
def table():
....
if syncRefresh():
refreshNow = True # refreshNow is the variable passed to the web page
and in the html page
{% if refreshNow %}
<meta http-equiv="refresh" content="1">
{% endif %}
refresh at a given minute and second → i.e. every hour at fixed time can be as follows:
<script type="text/javascript">
function refreshAt(minute, second) {
var date= new Date();
var hr = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if(m == minute && s == second)
{
window.location.reload(true);
}
setTimeout(function() { refreshAt(minute, second); },600);
};
</script>
Use this to refresh the page every 20 seconds.
<META HTTP-EQUIV="refresh" CONTENT="20">
Related
This is my countdown javascript code everyday on 23:00 of local time will finish and after 1 hour again will start to countdown for tomorrow and this continues. I wanted to know is it possible to add PHP code to this till after countdown finished everyday It adds "5" to my "Credit" column ("Credit" + 5 ) in my MySQL automatically ? appreciate for any kind of guidance.
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'Your match started!';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(23,0,0,0);
var myEnd = new Date()
myEnd.setHours(24,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<font face="Trebuchet MS">
<div id="foo" style="color: white; font-size: 14px; font-weight: bold;"></div>
Jquery Ajax is the way to go here i guess.
It seems like you are very new and might not know what ajax is.
In short with Ajax you can call a webpage url in the background. So You could call www.yourdomain.com/addCredits.php
It will do the same as if you would visit that url in your browser. Just write your SQL Code inside that addCredits.php File and you're done.
Just add something like this to your javascript:
$.ajax({url: "addCredits.php"});
You will have to embed jquery inside your document first though.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And also you might want to wait for that script to load before you call that function:
$( document ).ready(function() {
$.ajax({url: "addCredits.php"});
});
Edit:
Your Counter acutally seems to continue in a loop since it keeps up calling itself in the end.
But i would say just put it where your setTimeout is at the end of your function.
Edit2:
Here is an Example with a Clock, your code seems to be over-complicated to be honest. It doesn't really work when i put it in a fiddle aswell...
You could just use this instead:
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Here's the scenario, I have a time that counts the time_taken by a user. What I want is to get the exact time_taken based from the timer. For example, a user take an exam, then after he/she take the exam, the time_taken will be submitted (e.g. 1hr 25mins 23secs). Please see my code below.
$(document).ready(function(){
var d;
setInterval(function(){
d = new Date();
dates = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
$('#timeTaken').val(dates);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timeTaken" value="">
Here is Fiddle for the solution
https://jsfiddle.net/djzsddz6/1/
Ans Solution is below:
$(document).ready(function(){
var seconds = 0, minutes = 0 , hours = 0;
setInterval(function(){
seconds++;
if(seconds == 60){
minutes++
seconds = 0;
}
if(minutes == 60){
hours++
minutes = 0;
}
console.log(hours, minutes, seconds);
$('#timeTaken').val(`${hours}:${minutes}:${seconds}`);
}, 1000);
});
I don't really see the point to use an input there, you can just display in a span and when the form gets submitted take the time elapsed and send it with other data. Anyways, this should work for you:
$(document).ready(function () {
var time_start = new Date();
setInterval(function () {
var time_end = new Date();
var time_diff = (time_end - time_start);
// hours
var hours = Math.floor(time_diff / 1000 / 60 / 60);
// minutes
time_diff = time_diff - hours * 1000 * 60 * 60;
var minutes = Math.floor(time_diff / 1000 / 60);
// seconds
time_diff = time_diff - minutes * 1000 * 60;
var seconds = Math.floor(time_diff / 1000);
renderTime(hours, minutes, seconds);
}, 1000);
});
function renderTime (hrs, min, sec) {
var str = convertTime(hrs) + ":" + convertTime(min) + ":" + convertTime(sec);
$("#timeTaken").val(str);
}
function convertTime (val) {
return val < 10 ? "0" + val : val;
}
What's going on here is we have the time_start which does not change and we have setInterval function that is triggered every second. There we create new Date object, and the subtract the static one from it, which returns the time difference in milliseconds. We do the weird Math.flooring and subtracting, so we can have hours, minutes and seconds as an integers (not floats). Then we use render function to display the time inside an desired element.
Why I think it's a better solution then the others are, is that if you want to handle the user's page refresh you just need to save one variable to cookie or something else and it will work regardless of the page refresh.
Handling the page refresh would look like (with cookie saved for 2 hrs):
function updateTimeCookie () {
var time_now = new Date()
var value = JSON.stringify(time_now);
var expires = time_now.setTime(time_now.getTime() + 7200);
$.cookie("timeStart", value, { expires: expires });
};
// to get Date object from cookie: new Date(JSON.parse($.cookie("timeStart")))
To use $.cookie() you must first include jQuery Cookie Plugin.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Working fiddle without cookie: https://jsfiddle.net/qc3axmf4/1/
Working fiddle with cookie: https://jsfiddle.net/ta8bnzs0/2/
Rather than getting date at every second you can keep the counter in set interval which will updated at every second. At the time of submission you can perform division and modulus operation to get exact time taken
Example
$(document).ready(function(){
var timer =0;
setInterval(function(){
Timer +=1;
// Code for display in hr mm and ss
$('#timeTaken').val(dates);
}, 1000'
});
You can also convert second in time valueby using moment.js
Hope this helps you.
Happy coding
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);
I need some advice and logic in my problem.
So, I have an entrydate, from database, then the running current date, and a value of 10(double type in database). So, I know how to calculate the diff of the entrydate and current date, right. So I convert it to seconds then to a number(9.23165).
|Entry |Current Date|Diff(in number)|
|2:00:00 PM |2:30:00 PM | 5.00(Sample)|(First User)
So basically, as current date goes on, can PHP show the deduction on real time? Or I need to refresh? What I need is for it to display the deduction without refreshing. So basically, I need to know what I have to do. Maybe javascipt and ajax?
What you would need are a few Javascript/jQuery functions to update the browser in real time.
var myTimer;
var startTime;
function startTimer() {
stopTimer(); // Reset
startTime = new Date(); // Save to calculate difference
myTimer = setInterval(clockTicking, 1000);
}
function stopTimer() {
clearInterval(myTimer);
}
function clockTicking() {
var now = new Date();
var timeDiff = new Date(now - startTime); // constructor uses UTC, so use UTC date functions from here on
var hours = (timeDiff.getUTCHours() < 10) ? '0' + timeDiff.getUTCHours() : timeDiff.getUTCHours();
var mins = (timeDiff.getUTCMinutes() < 10) ? '0' + timeDiff.getUTCMinutes() : timeDiff.getUTCMinutes();
var secs = (timeDiff.getUTCSeconds() < 10) ? '0' + timeDiff.getUTCSeconds() : timeDiff.getUTCSeconds();
$("<element-where-you-display>").html(hours + ':' + mins + ':' + secs);
}
In Javascript you can call startTimer() to kick it off.
On a download page, I would like to have it so that when the page loads, a 10 second timer automatically starts. On the page, I would like some text to say something like "You can begin your download in 10 seconds..." Then, after the time is up a download button appears for people to click on and start their download.
How can I do this, and what code do I use to include it into a page?
See: http://jsfiddle.net/rATW7/
It's backwards-compatible and not so secure, but 10 seconds isn't much to worry about anyways.
You can use setInterval() to do this.
Note that make sure the countdownElement has an existing text node, which can be any whitespace. If you can't guarantee that, just use innerHTML or innerText/textContent.
window.onload = function() {
var countdownElement = document.getElementById('countdown'),
downloadButton = document.getElementById('download'),
seconds = 10,
second = 0,
interval;
downloadButton.style.display = 'none';
interval = setInterval(function() {
countdownElement.firstChild.data = 'You can start your download in ' + (seconds - second) + ' seconds';
if (second >= seconds) {
downloadButton.style.display = 'block';
clearInterval(interval);
}
second++;
}, 1000);
}
jsFiddle.
Noone could ensure that your intervals are exact, especially if tab (or browser) is inactive (see e.g. this post), so it's better to rely on time difference instead of counter:
var sTime = new Date().getTime();
var countDown = 30;
function UpdateTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var seconds = countDown - Math.floor(diff / 1000);
//show seconds
}
UpdateTime();
var counter = setInterval(UpdateTime, 500);
The working fiddle
A modification of the Fiddle provided by Yuriy which does NOT use JQuery, and works with hours as well if the # of seconds are large enough.
<div id="countdowntimertxt" class="countdowntimer">00:00:00</div>
<script type="text/javascript">
var sTime = new Date().getTime();
var countDown = 3700; // Number of seconds to count down from.
function UpdateCountDownTime() {
var cTime = new Date().getTime();
var diff = cTime - sTime;
var timeStr = '';
var seconds = countDown - Math.floor(diff / 1000);
if (seconds >= 0) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor( (seconds-(hours*3600)) / 60);
seconds -= (hours*3600) + (minutes*60);
if( hours < 10 ){
timeStr = "0" + hours;
}else{
timeStr = hours;
}
if( minutes < 10 ){
timeStr = timeStr + ":0" + minutes;
}else{
timeStr = timeStr + ":" + minutes;
}
if( seconds < 10){
timeStr = timeStr + ":0" + seconds;
}else{
timeStr = timeStr + ":" + seconds;
}
document.getElementById("countdowntimertxt").innerHTML = timeStr;
}else{
document.getElementById("countdowntimertxt").style.display="none";
clearInterval(counter);
}
}
UpdateCountDownTime();
var counter = setInterval(UpdateCountDownTime, 500);
</script>
I was writing a reply with code, but alex's reply is better than my quick & dirty solution.
Take into account that if you want to do something like what Rapidshare and others do, you will have to generate the link at the server side and retrieve it with AJAX, otherwise the only thing whoever wants to get the download immediately needs to do is to see the source code of your page ;-)
This is very simple, yes you can make it very easily. Here's the live link, where you can find the codding for making countdown timer , before download link appears : http://www.makingdifferent.com/make-countdown-timer-download-button-link-appears/
Cheers !!
You can use setTimeout function of javascript :
// make the button not visible
setTimeout(()=>{
// here make button visible and clickable
},10000)
// here 10000 -> 10 seconds timeout