Periodically Ping and show div on error - javascript

I currently have an image which gets pinged in order to only show a div if the local content is available.
But I think a better implementation is to periodically check for ping, at a 30 second interval, then show an #offline div if the image has not been pinged successfully. This is better as it considers that the status of the connection may change without the page having been reloaded.
Original script:
function ImgLoad(myobj){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){$("#online").show();}
}
I think I have managed to get the function to poll every 30 seconds, but I've not been able to show a div on error rather than if it pings successfully.
function checkping(){
function ImgLoad(myobj){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){$("#online").show();}
}
}
setInterval(function(){
checkping()}, 30000)

I've not been able to show a div on error
You're already using .onload, just use the corresponding .onerror :
oImg.onerror=function(){$("#error").show();}

Maybe consider "smart" polling instead, which checks your server for the image on incrementally increasing intervals instead of a fixed one.
This link may be of aide: https://github.com/blog/467-smart-js-polling

Related

The Exact time distance from button clicked to when received data to a website

I'm creating a chrome extension. I need to know when a user clicked on a specific button how many mili seconds will take long, to receive that command to website server. I have a web Worker that is connected to that website too. Could I get the exact time when a button clicked to when data received by website's server? It doesn't matter how many mili seconds take that the respond back to me, the time of receiving request to server after click is mu issue now. can someone help me please?
I'm looking for javascript code to get the time distance between button clicked and received that by website's server.
It is easy to get the time when button is clicked by finding that button and attaching an event handler on it, that calls performance.now()
const t0 = 0;
document.getElementById('buttonId').addEventListener('click',() => {
t0 = performance.now();
});
Detecting when the server response is received is not trivial. You might need to use the chrome.webRequest api.
Alternatively, a simpler way would be to look for side-effects of the request, that happen in the DOM. (A loader appearing and disappearing, data rows appearing, button being disabled and re-enabled, etc).
You can either poll for these changes, or use the mutationObserver api to detect when elements containing expected attributes are available in the DOM.
Let's say you are polling for the button being re-enabled, every 10ms:
const t1 = 0;
const interval = window.setInterval(() => {
if (!document.getElementById('buttonId').getAttribute('disabled')) {
t1 = performance.now();
requestTime = t1 - t0;
console.log(requestTime);
window.clearInterval(interval);
}
},10);

Why does setInterval not increment my clock properly in JavaScript?

I want to display the actual time in New York. I have a html div:
<div id="time"></div>
and also - I have a php script that returns the actual time:
<?php
date_default_timezone_set('UTC');
echo time();
?>
and it does it as a timestamp.
Now, I've created a js script:
var serverTime;
moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');
function fetchTimeFromServer() {
$.ajax({
type: 'GET',
url: 'generalTime.php',
complete: function(resp){
serverTime = resp.responseText;
function updateTimeBasedOnServer(timestamp) { // Take in input the timestamp
var calculatedTime = moment(timestamp).tz("America/New_York");
var dateString = calculatedTime.format('h:mm:ss A');
$('#time').html(dateString + ", ");
};
var timestamp = serverTime*1000;
updateTimeBasedOnServer(timestamp);
setInterval(function () {
timestamp += 1000; // Increment the timestamp at every call.
updateTimeBasedOnServer(timestamp);
}, 1000);
}
})
};
fetchTimeFromServer();
setInterval(function(){
fetchTimeFromServer();
}, 5000);
and the idea behind it is that I want to fetch the data from server, display it on my webpage, then increment it every second for five seconds and then fetch the time from the server again (to keep consistence with time on the server). And later on - continue with doing so, fetching the time, incrementing it for 5 seconds, fetching it again, etc.
It works... almost. After the webpage stays open for some time I can see the actual time, but it 'blinks', and I can see that it shows different times - it's hard to explain, but it looks like there is some time already in that div and new time tries to overlay it for each second. Seems like the previous time (content of this div) is not removed... I don't know how to create a jsfiddle with a call to remote server to fetch time from php, so I only have this information pasted above :(
What might be the problem here?
Since javascript is single threaded, setInterval may not acutally run your function after the delay. It adds the function to the stack to be run as soon as the processor is ready for it. If the processor has other events in the stack, it will take longer than the interval period to run. Multiple intervals or timeouts are all adding calls to the same stack for processing. To address this, you could use HTML5 web workers or try using setTimeout recursively.
Here is a good read on web workers: https://msdn.microsoft.com/en-us/hh549259.aspx

Is it possible to know how long a user has spent on a page?

Say I've a browser extension which runs JS pages the user visits.
Is there an "outLoad" event or something of the like to start counting and see how long the user has spent on a page?
I am assuming that your user opens a tab, browses some webpage, then goes to another webpage, comes back to the first tab etc. You want to calculate exact time spent by the user. Also note that a user might open a webpage and keep it running but just go away. Come back an hour later and then once again access the page. You would not want to count the time that he is away from computer as time spent on the webpage. For this, following code does a docus check every 5 minutes. Thus, your actual time might be off by 5 minutes granularity but you can adjust the interval to check focus as per your needs. Also note that a user might just stare at a video for more than 5 minutes in which case the following code will not count that. You would have to run intelligent code that checks if there is a flash running or something.
Here is what I do in the content script (using jQuery):
$(window).on('unload', window_unfocused);
$(window).on("focus", window_focused);
$(window).on("blur", window_unfocused);
setInterval(focus_check, 300 * 1000);
var start_focus_time = undefined;
var last_user_interaction = undefined;
function focus_check() {
if (start_focus_time != undefined) {
var curr_time = new Date();
//Lets just put it for 4.5 minutes
if((curr_time.getTime() - last_user_interaction.getTime()) > (270 * 1000)) {
//No interaction in this tab for last 5 minutes. Probably idle.
window_unfocused();
}
}
}
function window_focused(eo) {
last_user_interaction = new Date();
if (start_focus_time == undefined) {
start_focus_time = new Date();
}
}
function window_unfocused(eo) {
if (start_focus_time != undefined) {
var stop_focus_time = new Date();
var total_focus_time = stop_focus_time.getTime() - start_focus_time.getTime();
start_focus_time = undefined;
var message = {};
message.type = "time_spent";
message.domain = document.domain;
message.time_spent = total_focus_time;
chrome.extension.sendMessage("", message);
}
}
onbeforeunload should fit your request. It fires right before page resources are being unloaded (page closed).
<script type="text/javascript">
function send_data(){
$.ajax({
url:'something.php',
type:'POST',
data:{data to send},
success:function(data){
//get your time in response here
}
});
}
//insert this data in your data base and notice your timestamp
window.onload=function(){ send_data(); }
window.onbeforeunload=function(){ send_data(); }
</script>
Now calculate the difference in your time.you will get the time spent by user on a page.
For those interested, I've put some work into a small JavaScript library that times how long a user interacts with a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc.
Edit: I have updated the example to include the current API usage.
http://timemejs.com
An example of its usage:
Include in your page:
<script src="http://timemejs.com/timeme.min.js"></script>
<script type="text/javascript">
TimeMe.initialize({
currentPageName: "home-page", // page name
idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>
If you want to report the times yourself to your backend:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full http request into the document.onbeforeunload event.
The start_time is when the user first request the page and you get the end_time by firing an ajax notification to the server just before the user quits the page :
window.onbeforeunload = function () {
// Ajax request to record the page leaving event.
$.ajax({
url: "im_leaving.aspx", cache: false
});
};
also you have to keep the user session alive for users who stays long time on the same page (keep_alive.aspxcan be an empty page) :
var iconn = self.setInterval(
function () {
$.ajax({
url: "keep_alive.aspx", cache: false });
}
,300000
);
then, you can additionally get the time spent on the site, by checking (each time the user leaves a page) if he's navigating to an external page/domain.
Revisiting this question, I know this wouldn't be much help in a Chrome Ext env, but you could just open a websock that does nothing but ping every 1 second and then when the user quits, you know to a precision of 1 second how long they've spent on the site as the connection will die which you can escape however you want.
Try out active-timeout.js. It uses the Visibility API to check when the user has switched to another tab or has minimized the browser window.
With it, you can set up a counter that runs until a predicate function returns a falsy value:
ActiveTimeout.count(function (time) {
// `time` holds the active time passed up to this point.
return true; // runs indefinitely
});

How to have a timer which cannot be modified in javascript?

Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());

image polling through javascript

I need to poll an image using javascript and need to perform an action once the image is found at its position. This is the code I have written for this task.
/*----Image handling script starts here----*/
var beacon = new Image();
beacon.onload = function() {
console.log('Image found');
console.log(this.width,this.height);
window.clearInterval(timer);
};
beacon.onerror = function(){
console.log('Image not found');
}
var timer = window.setInterval(function(){
console.log('sending the request again');
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif";
},2000);
/*----Image handling script ends here----*/
Problem is that, after one GET request, the response gets cached and request don't get sent everytime I set src. If you examine NET tab, it sends request only on first src set and caches the response.
I need to send a fresh request for image every time my code sets the src. Any workarounds?
Change your src to include the current EPOCH time as a variable.
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" +
date.getTime();
Using a different variable in the query string each time will miss out caching, because as far as the browser is concerned, the image is different (or potentially could be) each time you request the image, and there is no limit to the amount of times you ask, as time hopefully will not stop...
Request the image with a different query string each time. The browser will treat it as a unique URL and won't have it in the cache. You can probably get away with this because it's likely the web server will ignore anything in the query string when requesting an image. The following should make 100 requests:
for (var i=0; i<100; i++)
{
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" + i;
}

Categories

Resources