setInterval not working as expected with phonegap - javascript

I have set up a function which checks the location of the user every X mins using setInterval() which works for the most part as expected. However after some time of the phone being inactive the intervals seem to stretch out, ie if it was set to 5 mins it could take up to an hour to check again if the phone has been inactive for some time. This is intended to keep going 24/7 so the phone being inactive will be common.
Is this a known problem or is there something I should be doing to prevent this?
var onDeviceReady = function(){
var preCheckGPSInterval = setInterval(function(){
var watchID = navigator.geolocation.watchPosition(
function(position){
if(position.coords.accuracy < 100){
navigator.geolocation.clearWatch(watchID);
//code to execute
}
},
function(error){
console.log("error");
},
{enableHighAccuracy: true}
);
}, 300000);
}
document.addEventListener("deviceready", onDeviceReady, false);

Is this a known problem or is there something I should be doing to prevent this?
#Marty,
this is not a problem. This is the way it is supposed to work. If an App is NOT in the foreground, the app will have it's resources cleared from memory and possibly stored in swap space.
As suggested, you will need to force your app to run in the background. This article will help. 7 things you should know about Android Manifest xml file.

Related

Mstsc with auto-credentials over IE?

Currently Im trying to do an automatic logon over rdp with the Internet Explorer.
Basically what I'm trying to do is opening an ActiveXObject which then calls cmdkey to store the credentials temporary
var ws = new ActiveXObject("WScript.Shell");
setTimeout(function(){
ws.Exec("cmdkey /delete:"+servername+" ");
}, 100);
setTimeout(function(){
ws.Exec("cmdkey /generic:"+servername+" /user:"+username+" /pass:"+password+"");
}, 500);
setTimeout(function(){
ws.Exec("mstsc /v:"+servername+"");
}, 800);
setTimeout(function(){
new ActiveXObject("WScript.Shell").Exec("cmdkey /delete:"+servername+" ");
}, 20000);
First I thought the problem would be the cmdkey delete running before the mstsc could establish the connection, but even with a 20s timeout it still wasn't really working.
With "Not really working" I mean it works on some computers and on some computers not. And this is either Account-based (on the computer) or just generally working on a computer. Why is that? (I can't tell)
I'm currently testing it on IE11.0.48 with the js running locally on xmapp.
Does someone know the problem? or am I doing something wrong? (OR would there even be a better solution for this?)
//EDIT1: ActiveX is allowed internally and the mstsc gets called everytime but the autologon is the thing that doesnt work (at least not everytime)

Time an event using javascript/jquery

Is it possible to trigger an event on a website, say 30 seconds after someone hits the site, even if they move between pages, or would that require some server side coding?
Thanks in advance.
You can use session storage to accomplish this. Javascript Storage data persists across pages and refreshes. Here is some info: http://www.w3schools.com/html/html5_webstorage.asp
// SET THIS ON THE FIRST VISIT. CHECK IF ALREADY SET.
if(typeOf(localStorage.getItem('timer')) == 'undefined'){
localStorage.setItem("timer", "0");
}
setInterval(function(){
// ADD 1 SECOND TO SESSION TIMER
localStorage.setItem("timer", localStorage.getItem("timer")++);
if(localStorage.getItem("timer") == 30){
// TRIGGER YOUR EVENT ON 30 SECONDS
}
}, 1000);

How to check idle time using jQuery and PHP?

I have a script that uses PHP SESSION. I manage PHP sessions using a class. Within this class I have a method that returns how many seconds remaining before the session expires.
Also, Evey time the user refresh the page or open a new page (new request to the server) the idle time counter starts over $_SESSION['MA_IDLE_TIMEOUT'] = time()+900;
What I am looking to do is display a dialog message 2 minutes before the PHP session expire and check if the user is still on the page or not. If the use clicks "Keep working" then the jQuery script will send PHP AJAX request to renew the session $_SESSION['MA_IDLE_TIMEOUT'] = time()+900;. If the user did not click anything or clicked on "Log out" then the session ends and the user is redirected to the login page.
I did find a nice plugin that will somewhat does the Job jquery-idle-timeout
The issue with this plugin is that it checks if the user is idle using JavaScript (if the keyboard/mouse) are being used. Here is the senario where this script does not help me: lets say my PHP sessions has a limit on 15 minutes/ 900 seconds. A user is reading a super long article on the same page. He/she will be scrolling, they are not really idle "from JavaScript perspective" but from a PHP perspective the use is idle. Then after 20 minutes the user refresh the page, then the user will be logged out since he/she have not sent a new request to the PHP server for over the 900 seconds limit.
How can I solve this problem? is there a better plugin to does the trick? if there something I missed in this plugin that will solve my problem?
Thanks
If the user is not making requests, and is not moving the mouse or keyboard or touching the device, etc., then from the app's point of view the user is "idle" even if their eyeballs are not.
If the user is scrolling you can use javascript to listen for scroll events (via onscroll, for example), but this will not be 100% reliable because (1) depends on javascript, and (2) doesn't work if you are viewing a short article or using a tall/large format monitor (like the ones you can rotate 90 degrees, for example).
Perhaps you could handle this differently: use cookies, single sign-on or similar techniques to pre-authenticate or automatically authenticate requests so that the user's session can safely die and be restarted without the user having to manually login.
The other way you could handle this is to maintain a "ping" process that routinely pings the server (via setInterval(), for example) to keep the session alive, and uses a separate timeout (maybe something like the "Authentication timeout" that ASP.NET uses) to keep track of when the "idle" user should be logged out. Then user actions such as scrolling, requesting pages, focusing in fields, moving mouse, etc., can do a "ping reset" that resets the idle counter to 0.
Example / Concept - leaving as exercise for reader to perfect it:
var idleTime = 0; // how long user is idle
var idleTimeout = 1000 * 60 * 20; // logout if user is idle for 20 mins
var pingFrequency = 1000 * 60; // ping every 60 seconds
var warningTime = 1000 * 60 * 2; // warning at 2 mins left
var warningVisible = false; // whether user has been warned
setInterval(SendPing, pingFrequency);
setInterval(IdleCounter, 1000); // fire every second
function IdleCounter() {
idleTime += 1000; // update idleTime (possible logic flaws here; untested example)
if (console) console.log("Idle time incremented. Now = " + idleTime.toString());
}
function SendPing() {
if (idleTime < idleTimeout) {
// keep pinging
var pingUrl = "tools/keepSessionAlive.php?idleTime=" + idleTime;
$.ajax({
url: pingUrl,
success: function () {
if (console) console.log("Ping response received");
},
error: function () {
if (console) console.log("Ping response error");
}
});
// if 2 mins left, could show a warning with "Keep me on" button
if ((idleTime <= (idleTimeout - (idleTimeout - warningTime))) && !warningVisible) {
ShowTimeoutWarning();
}
} else {
// user idle too long, kick 'em out!
if (console) console.log("Idle timeout reached, logging user out..");
alert("You will be logged off now dude");
window.location.href = "logoff.aspx"; // redirect to "bye" page that kills session
}
}
function ShowTimeoutWarning() {
// use jQuery UI dialog or something fun for the warning
// when user clicks OK set warningVisible = false, and idleTime = 0
if (console) console.log("User was warned of impending logoff");
}
function ResetIdleTime() {
// user did something; reset idle counter
idleTime = 0;
if (console) console.log("Idle time reset to 0");
}
$(document) // various events that can reset idle time
.on("mousemove", ResetIdleTime)
.on("click", ResetIdleTime)
.on("keydown", ResetIdleTime)
.children("body")
.on("scroll", ResetIdleTime);
I use a time cookie to log out an inactive user like this:
`$time = time();
// 5 minutes since last request
if(!empty($_COOKIE['_time'] && $time - $_COOKIE['_time'] >= 300)
{
// log user out
}
setcookie('_time', $time, '/');`
Hope this helps.

jQuery Ajax timeout kicks in on Windows browser but not Android

So I've this piece of code which checks for internet speed and returns back some result. In order to deal with non-connectivity or disconnect issues while the speed check is going on, I put a timeout wait of 10 seconds.
This timeout works fine on a desktop browser (I started the test, pulled the plug, and after 10 seconds the error function kicked in.
But while trying to run the same page on Android browser, the error function does not respond even after 30-40 seconds or so.
This makes me believe this has got something to do with Android settings and was hoping any one having knowledge in that area would point me in the right direction. Here is the code btw:
$.ajax({
url:'internet-speed.php',
timeout: 10000,
error: function(x, t, m){
if(t==="timeout")
{
$('span#wait').html('Timed out');
}
else
{
$('span#wait').html('Something went wrong');
}
},
success:function(data)
{
$('span#wait').html('Your speed is '+data+'kbps');
}
});

<video>.currentTIme doesn't want to be set

I'm trying to write a piece of Javascript that switches between two videos at timed intervals (don't ask). To make matters worse, each video has to start at specific place (about ten seconds, and again, don't ask.)
I got the basics working by just using the YUI Async library to fire to switch the videos at intervals:
YUI().use('async-queue', function (Y) {
// AsyncQueue is available and ready for use.
var cumulativeTime = 0;
var q = new Y.AsyncQueue()
for (var x = 0; x < settings.length; x++) {
cumulativeTime = cumulativeTime + (settings[x].step * 1000)
q.add( {
fn: runVideo,
args: settings[x].mainWindow,
timeout: cumulativeTime
})
}
q.run()
});
So far, so good. The problem is that I can't seem to get the video to start at ten seconds in.
I'm using this code to do it:
function runVideo(videoToPlay) {
console.log('We are going to play -> ' + videoToPlay)
var video = document.getElementById('mainWindow')
video.src = '/video?id=' + videoToPlay
video.addEventListener('loadedmetadata', function() {
this.currentTime = 10 // <-- Offending line!
this.play();
})
}
The problem is that this.currentTime refuses to hold any value I set it to. I'm running it through Chrome (the file is served from Google Storage behind a Google App Engine Instance) and when the debugger goes past the line, the value is always zero.
Is there some trick I'm missing in order to set this value?
Thanks in advance.
Try use Apache server.
setCurrentTime not working with some simple server.
ex) python built in server, php built in server
HTTP server should be Support partial content response. (HTTP Status 206)

Categories