Run a function on load and then every 10 minutes - javascript

Is there a way to execute a javascript function when the page loads and then not again for another 10 minutes. Even if user browses to another page? If they dont want the function to run again until the 10 minutes is up?

Simply create the function you want to execute onload, call it once on DOM ready, and then use setTimeout()
<script type="text/javascript">
function doSomething() {
alert("Doing something here");
}
window.onload = function () {
doSomething(); //Make sure the function fires as soon as the page is loaded
setTimeout(doSomething, 600000); //Then set it to run again after ten minutes
}
</script>
Edit:
Didn't notice the part about even if they're on another page. If it's another page on your website, you could set a cookie once the page loads, and include a timestamp for when the cookie was set. In the window.onload of the rest of your pages, you can then read that timestamp, and calculate whether 10 minutes have passed or not. If it has, call the function again.
Edit: 10 minutes is 600000 milliseconds

Even if user browses to another page?
Nope. Once your page closes, you no longer have control over what happens.

function callfunction () {
// do something
}
window.onload = function () {
// Initial function call
callfunction();
setInterval(function () {
// Invoke function every 10 minutes
callfunction();
}, 600000);
}

Use setInterval or setTimeout to make something happen in the future.
But as soon as the user leaves your page those timers will be cancelled - the entire content will be unloaded.

You can use:
setTimeout(alert('After 10 secs'),10000);

If the user visits another website in the same tab, you're out of luck; once your webpage is closed the javascript dies.
However you're in luck if the user is just visiting other pages on your website. You can do this as follows... but it requires a fundamental redesign of your website. You'd have to use a framework which wraps all link-clicks in XHRs (XML HTTP Requests) and replaces the page with the new data, giving you the illusion that you are clicking links (which you are, but the browser never refreshes the page). This can be done with an iframe or not. This is how GMail works.
You could code such a framework yourself, but you're better off using a framework which has url-rewriting support for faking a history (or else your website won't work well with user histories).
To answer your question about the "every 10 minutes", use setInterval(myFunction, 10*60*1000) (which may have issues in some browsers due to optimizations).

Assuming that you use a server language, you can set a session variable at startup (startup date/time) and then, using setInterval, compare current time with startup date/time.

you're required to save the state in a remote server.
this is your steps:
the javascript function loads, no matter where or when, it loads.
when loaded (the javascript fn) calls a remote server using a UNIQUEID, that can be obtained via cookies, or session variable, from the loggedin user id...whatever.
you send a request to a server using such UNIQUEID (via ajax, normally), your server will tell you if such process must start again or you should avoid it (a page jump as an example or a page refresh in a different browser using the same login, it depends on your business logic).
the response from step3 is used to execute/initialize the javascript loader or not.

Related

Load data without hard refresh

Case: An user purchases an airplane ticket from American Airline on my website. It takes an hour for the order to get processed, after which I need to show a navigation tab.
Question: I don't want the user to refresh the page to load the data. Is there something that can trigger an API call an hour later after the user's ticket purchase?
I'm using AngularJS, Express, NodeJS.
Update:
I thought about using setTimeout(fn, delay) to initiate a timer and then use clearInterval(id) to close it after request success. However, the browser executes on a single thread asynchronously so the timer delay is not guaranteed. In addition:
If the user put the computer to sleep, the setTimeout would freeze.
If the user switched tab, the setTimeout function becomes inaccurate.
The setTimeout behavior could be different in different browsers.
I also consider about node-cron, but I still need to make a node call automatically because the navigation controller is loaded on app start. This means the user still has to do a hard refresh to see the navigation tab.
Is there a way to use browser cache to do it?
With javascript, you can dynamically load and change data.
for example below code will get triggered every minute and inside, you can perform asynchronous tasks such as calling http requests, and dynamically update value.
setInterval(function(){
//perform async task and get new value
document.getElementById('DOM').value = "NEW VALUE";
}, 60000);

Javascript page call function

I have javascript page that calling another page.
when the second page is called, I send request data to sql server to see how many
time the second page is called.
But always see that just once.
I've added dynamic querystring to prevent cache from browser
this is my code:
for(i=1;i<=30;i++)
{
var q="eeee?id=" + i;
window.location=q;
}
But alwayes see these 2 records in database instead of 31 records:
javacall ==> first page that has java call function
eeee?id=30
why page is called in 30th call and not from 1 to 30, for example:
javacall
eeee?id=1
.
.
.
eeee?id=30
The browser doesn't check to see if location has changed until the JavaScript has stopped running (it is too busy running the JavaScript until then).
When the loop gets to the end, it will be set to the last value. At the point, the browser registers that it has changed and loads the new URL.
If that wasn't the case, then the first change to it would cause the browser to leave the current pageā€¦ which will destroy the execution environment the script was running it, abort the script and cause the subsequent URLs to not be requested.
If you want to make multiple HTTP requests from JavaScript, then use Ajax. You'd normally do this through the XMLHttpRequest object.

Killing session when browser is closing

I need to kill the session when the user closes the browser or redirects into some other page.
I can see the following options of achieving this functionality:
Use no session login. It's not my case, because I'd have to change a lot and I also use sessions for some other data.
I could use something like this:
window.onunload = window.onbeforeunload = (function () {
...
})
And from this code call the action that cleans the session and performs logoff.
Sounds nasty but what is also important - this JavaScript code works only in IE.
I could create some nasty code that uses some dummy calls, let's say every minute, just to say the server that the user is still alive.
But it's really nasty. It would use useless load on the server, lots of useless calls and in the case if some call was lost(because of the connection issue or something) the user would logg off.
Any other options?
You've left off #4: Don't do anything, have sessions time out after a reasonable period (say, 20 minutes); if they try to do something on that page after being gone for 20 minutes, just show a page telling them their session has expired and to log in again. That's usually the simplest option.
If you don't want to do that, #3 is really your only viable option, but once/minute is probably overkill. Set the session timeout to 20 minutes, remember when the user has done something, and if they're idle for (say) 15 minutes do a proactive call on their behalf. But even then, I'd limit how much I'd do this, after a couple of hours you might want to just redirect them to the login page.
I think this answer is the right way to go:
In javascript, how can I uniquely identify one browser window from another which are under the same cookiedbased sessionId
Set a unique window id:
window.windowIdClient = "{978d-478ahjff-3849-dfkd-38395434}"; //or another randomly generated id.
Store that windowId in the database, along with the ip-address and the session-id. If those three do not match than the user is logged out.
In addition, if didn't think of T.J. Crowder's option, I use it myself.

window.location.reload(true) working inconsistently

I've been working on an automatic log-out functionality for my web page. As a part of that, I implemented the window.location.reload(true) in 3 different places in my code. Two of them are automatic, one is attached to a link. The link always works, but the automatic ones don't always work, and I don't understand why.
For the automatic logouts, one set by a debouncer:
var userActionTimeout = debounce(function(e) {
console.log("inaction timeout, reloading page");
window.location.reload(true);
},15000;);
$(document.body).on('mousemove keydown click scroll',userActionTimeout);
Which theoretically should reload the page after a certain amount of inactivity.
The other two uses happen after certain types of AJAX data submission (e.g. blatantly wrong data sent that could only happen if the client was modified) trigger a log out. Of course, any further AJAX submissions are ignored by the server, and the next page the server will serve the client is a login page. In the event this happened inadvertently, AJAX sends the client an error message that includes the following:
refresh to continue session
I also implemented a timeout that also happens if this link is served, which happens after the AJAX response is received:
if (typeof response._forceRefresh !== 'undefined' && response._forceRefresh) {
console.log('reload firing');
/*
some code to insert the link into a spotlight here
*/
setTimeout(function(){console.log('reloading in 3s...');},7000);
setTimeout(function(){
console.log('reloading...');
window.location.reload(true);
},10000);
}
However the issue I'm having is this: Most of the time, the debounce page reload works (tested in firefox & chrome), however occasionally it doesn't. The link always works, but the AJAX response reload is about 50/50. I know it receives the response from the server since the link shows up, but quite often it doesn't actually automatically reload the page.
What is going on?
When ever I get inconsistency on a web page, it usually involves caching that I didn't realize was happening. If you haven't already, look through your project with that in mind and see if there is an effected location that you can force it not to cache a page.
Another idea might be to try using the meta refresh element. There is another thread where this is suggested: auto logout idle timeout using jquery php

Keep timer (setInterval) running while reloading page

Once I load a webpage, I insert some Javscript via the console. I was wondering if it's possible for me to, using either Javascript or jQuery, reload the page (not from cache) while keeping a setInterval that I have running. I'm familiar with location.reload(), but that terminates it.
When you reload a page, the entire page context including all running JS is completely destroyed. You cannot keep a setInterval() running while its host page is reloaded.
You can create a signal for the new page to start the interval going again itself using a cookie, query parameter or local storage value (query parameter is probably the most appropriate). If you go this way, then you need to code the page to look for a specific query parameter and if it finds it, then the page should start the designated setInterval() itself. You can even pass some data in the query parameter (such as how much more time until the next interval should fire, etc...).
Another option is to not actually reload the page, but instead to refresh the content manually by getting new content via an ajax call and then inserting it into the current page. This allowed the current page context and running interval timers to continue running.
Not possible unless you fetch the page using Ajax request, then replace the body while the setInterval Is working

Categories

Resources