My question is Client time only displayed, But want to display server time every seconds.
function GetCount(ddate,iid){
var date = new Date();
dateNow = date;
// if time is already past
if(amount < 0){
}
// else date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
document.getElementById(iid).innerHTML=days;
document.getElementById('countbox1').innerHTML=hours;
document.getElementById('countbox2').innerHTML=mins;
document.getElementById('countbox3').innerHTML=secs;
setTimeout(function(){GetCount(ddate,iid)}, 1000);
}
}
If you want to avoid all that network traffic checking the time with the server every second just: (1) have the server pass the time in a way that you store in a JS variable on page load; (2) also store the client time as at page load; (3) use setInterval to update the time (every 1000 milliseconds or as often as you want) by getting current client time minus client time at page load as an offset of server time at page load. (Obviously this will all go wrong if the user updates their PC clock while your page is running, but how many users would do that? And would it be the end of the world if they did?)
If you really want the actual server time every second - why? Seems a bit of a waste of bandwidth for little if any benefit, but if you must do it use Ajax as already suggested. If you're not familiar with Ajax I'd suggest using Google to find some tutorials - if you use JQuery you can do it with only a couple of lines of code. Easy.
Or put your onscreen clock in an IFRAME that repeatedly reloads itself. Just because I sometimes miss the days of IFRAMEs.
If you run into the issue that the server time is different from the client-side clock, I lookup a server time delta in minutes just once, and then I add it to the minutes of a new Date():
var refDateTime = new Date();
refDateTime.setMinutes(refDateTime.getMinutes() + getServerTimeDelta());
// ...
var serverTimeDelta;
function getServerTimeDelta(recalc) {
var xmlHttp;
if (recalc || !serverTimeDelta) {
try {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
} catch(err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch(err2) { /* swallow it */ }
}
if (xmlHttp) {
xmlHttp.open('HEAD', window.location.href.toString(), false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
var serverDateTime = xmlHttp.getResponseHeader("Date");
if (serverDateTime) {
var dateNow = new Date();
var serverDate = new Date(serverDateTime);
var delta = serverDate.getTime() - dateNow.getTime();
// Convert to minutes
serverTimeDelta = parseInt((delta / 60000) + '');
if (!serverTimeDelta) serverTimeDelta = 0.01;
} else {
serverTimeDelta = 0.011; // avoid auto recalc
}
} else {
serverTimeDelta = 0.012;
}
}
return serverTimeDelta;
}
You need your server to supply the time to JavaScript, either on page load or via XMLHttpRequest.
To get the server time from the client side in javascript you will need to make an ajax call.
Do you know how to make that type of call?
You will basically make another page (or web method etc) which displays/returns the time. You will then use a XMLHttpRequest object to make the call and get the result.
Related
I am trying to sync my laptop's time with a server's time in milli seconds. I'm using this snippet:
let diffTime = 0;
syncTimeFromServer=function(){
n=new XMLHttpRequest;
n.onreadystatechange=function(){
if(n.readyState===XMLHttpRequest.DONE&&n.status===200){
let d11 = new Date().getTime();
let lastServerDate = Number(tttt.msFormat.split('/Date(')[1].split(')/')[0]);
diffTime = new Date().getTime - lastServerDate;
}
};
dBefore = new Date().getTime();
var ttt=resetTimeZoneToTehran(new Date);
n.open("GET","/Home/GetDateTime?t="+ttt,!0);
n.send()
};
myBtn.addEventlistener('click',()=>{
diffTime += waitingForServerRespons;
console.log('diff time between my Local to Server:',diffTime);
})
I get the diff from XHR request then in Network tab of chrome I got the waiting Time For Server respond As you can see in image:
How to get waitingForServerRespons
The question is why difference between serverTime and myTime isn't stable in all cases? In some cases difference is 120 ms and others about 140 ms. So there is about 20 ms difference in all cases to each other. but I want to get exact different time of server and my laptop's in all cases to set that difference to my new Date() instances. Where have I do it wrong? Any suggestion would be great.
something is wrong. My calculations or that link which is providing the server time. Which its results is like this:
{"hour":3,"minute":13,"second":29,"msFormat":"/Date(1674863009736)/"}
I'm using a script that grab a json informations from a Web App using their API and my ajax code, but if something in the Web app change, I still grab the old informations, because we have difference in Time Zone. So if I add 11 hours in My computer I get the new Informations.
So it's possible to change local time to another timezone using javascript ? Thanks.
UPDATE
I'm using ajax with Javascript, not jQuery
function getInfos(url) {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.send(null);
oReq.responseType = "text";
oReq.onreadystatechange = function()
{
if (oReq.readyState == 4)
{
var resp = JSON.parse(oReq.responseText)
// Do Something with Data
}
}
}
You could try using timesonze-js. According to their documentation you should initialize it like this:
timezoneJS.timezone.zoneFileBasePath = '/path/to/your/tz/folder';
timezoneJS.timezone.init();
Then you can use it like so:
var date = new timezoneJS.Date('04/30/2014', 'America/Chicago');
Not exists a function to change timezone
javascript automatically takes the time zone of your computer
one way would
Use UTC() method
after
add or subtract the minutes of difference
with this you will have the time in any time zone
use gettimezoneoffset to get the minutes of difference
This sounds a bit orthodox, i'll admit.
However i was wondering if there was a way to load a specific website using Javascript/Jquery/Ajax or HTML5?
Reason i ask is because i'm aware there's a method for using cronjobs, but i'm curious to know if there's another method that does not require cron jobs in order for it to function.
By load a specific page i'm referring to anything really, perhaps a set
of words or an iframe.
Derek
You would have to have a page already loaded, so let's say this is the javascript in index.html:
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime();
that will see the milliseconds since midnight. Now the code below will redirect to a page (or text) if it's within 1 minute of midnight:
document.onload = function()
{
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime();
if(diff <= 60000)
{
//Un-comment first line to go to page, second to change text of page
//window.location.href = 'pageToLoad.html';
//document.body.innerHTML = 'yourText';
}
}
Like you already know there are cron jobs (server side) wich allow you to execute some php scripts at a precise time on your server/host.
If you want that your users see different pages at a certain hour of the day(or a specific time) by loading different content with ajax . Here is a very short example.
1.ajax function for modern browsers(chrome,safari,ie10,ios,android..)
2.time check
3.get night or day content.
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
var h=new Date().getHours();
// if it's after 12pm & before 6am it returns night else day.
nightday=(h>0&&h<6?'night':'day')+'.php';
//get the data from file 'day.php' or 'night.php'
ajax(nightday,function(){
//this.response is the content
console.log(this.response);
});
if you want to execute this just once:
window.onload=function(){
var c=new XMLHttpRequest,h=new Date().getHours();
c.open('GET',(h>0&&h<6?'night':'day')+'.php');
c.onload=function(){console.log(this.response)};
c.send()
}
And from here there are now various ways to check what time it is.
on every click,on some specific clicks,setTimeout(bad),setIntervall(bad)..and much more.
night.php
<?php
//load the content for night
?>
day.php
<?php
//load the content for day
?>
I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.
I want to run a JavaScript code to ping 4 different IP addresses and then retrieve the packet loss and latency of these ping requests and display them on the page.
How do I do this?
You can't do this from JS. What you could do is this:
client --AJAX-- yourserver --ICMP ping-- targetservers
Make an AJAX request to your server, which will then ping the target servers for you, and return the result in the AJAX result.
Possible caveats:
this tells you whether the target servers are pingable from your server, not from the user's client
so the client won't be able to test hosts its LAN
but you shouldn't let the host check hosts on the server's internal network, if any exist
some hosts may block traffic from certain hosts and not others
you need to limit the ping count per machine:
to avoid the AJAX request from timing out
some site operators can get very upset when you keep pinging their sites all the time
resources
long-running HTTP requests could run into maximum connection limit of your server, check how high it is
many users trying to ping at once might generate suspicious-looking traffic (all ICMP and nothing else)
concurrency - you may wish to pool/cache the up/down status for a few seconds at least, so that multiple clients wishing to ping the same target won't launch a flood of pings
The only method I can think of is loading e.g. an image file from the external server. When that load fails, you "know" the server isn't responding (you actually don't know, because the server could just be blocking you).
Take a look at this example code to see what I mean:
/*note that this is not an ICMP ping - but a simple HTTP request
giving you an idea what you could do . In this simple implementation it has flaws
as Piskvor correctly points out below */
function ping(extServer){
var ImageObject = new Image();
ImageObject.src = "http://"+extServer+"/URL/to-a-known-image.jpg"; //e.g. logo -- mind the caching, maybe use a dynamic querystring
if(ImageObject.height>0){
alert("Ping worked!");
} else {
alert("Ping failed :(");
}
}
I was inspired by the latest comment, so I wrote this quick piece of code.
This is a kind of "HTTP ping" which I think can be quite useful to use along with XMLHttpRequest calls(), for instance to figure out which is the fastest server to use in some case or to collect some rough statistics from the user's internet connexion speed.
This small function is just connecting to an HTTP server on an non-existing URL (that is expected to return a 404), then is measuring the time until the server is answering to the HTTP request, and is doing an average on the cumulated time and the number of iterations.
The requested URL is modified randomely at each call since I've noticed that (probably) some transparent proxies or caching mechanisms where faking results in some cases, giving extra fast answers (faster than ICMP actually which somewhat weird).
Beware to use FQDNs that fit a real HTTP server!
Results will display to a body element with id "result", for instance:
<div id="result"></div>
Function code:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
For instance, launch with:
fp = new http_ping("www.linux.com.au");
Note that I couldn't find a simple corelation between result figures from this script and the ICMP ping on the corresponding same servers, though HTTP response time seems to be roughly-exponential from ICMP response time. This may be explained by the amount of data that is transfered through the HTTP request which can vary depending on the web server flavour and configuration, obviously the speed of the server itself and probably other reasons.
This is not very good code but I thought it could help and possibly inspire others.
The closest you're going to get to a ping in JS is using AJAX, and retrieving the readystates, status, and headers. Something like this:
url = "<whatever you want to ping>"
ping = new XMLHttpRequest();
ping.onreadystatechange = function(){
document.body.innerHTML += "</br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "</br>" + result + "</br>";
}
}
}
ping.open("GET", url, true);
ping.send();
Of course you can also put conditions in for different http statuses, and make the output display however you want with descriptions etc, to make it look nicer. More of an http url status checker than a ping, but same idea really. You can always loop it a few times to make it feel more like a ping for you too :)
I've come up with something cause I was bored of searching hours after hours for something that everyone is saying "impossible", only thing I've found was using jQuery.
I've came up with a new simple way using Vanilla JS (nothing else than base JavaScript).
Here's my JSFiddle: https://jsfiddle.net/TheNolle/5qjpmrxg/74/
Basically, I create a variable called "start" which I give the timestamp, then I try to set an invisible image's source to my website (which isn't an image) [can be changed to any website], because it's not an image it creates an error, which I use to execute the second part of the code, at this time i create a new variable called "end" which i give the timestamp from here (which is different from "start"). Afterward, I simply make a substraction (i substract "start" from "end") which gives me the latency that it took to ping this website.
After you have the choice you can store that in a value, paste it on your webpage, paste it in the console, etc.
let pingSpan = document.getElementById('pingSpan');
// Remove all the way to ...
let run;
function start() {
run = true;
pingTest();
}
function stop() {
run = false;
setTimeout(() => {
pingSpan.innerHTML = "Stopped !";
}, 500);
}
// ... here
function pingTest() {
if (run == true) { //Remove line
let pinger = document.getElementById('pingTester');
let start = new Date().getTime();
pinger.setAttribute('src', 'https://www.google.com/');
pinger.onerror = () => {
let end = new Date().getTime();
// Change to whatever you want it to be, I've made it so it displays on the page directly, do whatever you want but keep the "end - start + 'ms'"
pingSpan.innerHTML = end - start + "ms";
}
setTimeout(() => {
pingTest();
}, 1000);
} // Remove this line too
}
body {
background: #1A1A1A;
color: white
}
img {
display: none
}
Ping:
<el id="pingSpan">Waiting</el>
<img id="pingTester">
<br> <br>
<button onclick="start()">
Start Ping Test
</button>
<button onclick="stop()">
Stop
</button>
function ping(url){
new Image().src=url
}
Above pings the given Url.
Generally used for counters / analytics.
It won't encounter failed responses to client(javascript)
I suggest using "head" to request the header only.
xhr.open('head', 'asstes/imgPlain/pixel.txt' + cacheBuster(), true);
and than ask for readystate 2 - HEADERS_RECEIVED send() has been called, and headers and status are available.
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) { ...
Is it possible to ping a server from Javascript?
Should check out the above solution. Pretty slick.
Not mine, obviously, but wanted to make that clear.
You can't PING with Javascript. I created Java servlet that returns a 10x10 pixel green image if alive and a red image if dead. https://github.com/pla1/Misc/blob/master/README.md