Make Angular Controller Run Continuously Through Page Refresh - javascript

In short, I am wondering if it possible to make an Angular controller pick up where it left off after the page is refreshed.
To give more details, suppose I have a controller that is responsible for running timers on several DOM items on that page. I click start, timer runs until I stop it. Now, when the page is refreshed, the timer and all values are re-set to zero. How could I make them continue from where they were immediately before the refresh event? In fact, is there a way to account even for the time it took for the page to refresh?
Currently, Angular is doing the timing. Should I try to switch timing to Node side?
Any advice is appreciated.

I strongly recommend that you try to switch the timer values to Node's side. That's the only way you can get the timers really updated and synchronized with your server.
I do not encourage that you store the timer values on storage, you will never have a reliable data, since the user can easily modify it.

Since there is no persistence of state between page loads in javascript you would need to store the timer state. localStorage would be one option
Not clear if timer is working towards a fixed time or tracking elapsed time. Store wht works best to allow you to reactivate when service runs again

Related

How to make setInterval work correctly in background tab

I'm using setInterval (within 3 Tampermonkey scripts) to check three different public websites every few seconds, so I can be alerted when specific text appears. These alerts are for freelance work offers, which can expire within seconds so I have to be quick.
It all works correctly, except when I'm working in a different tab or app, then that after about 6 minutes, setInterval starts to "trigger" for the background tab once per minute instead of once every few seconds.
Any suggestions how to fix this? Is it possible to use Date.now() in some way?
Note, I'm a complete beginner, willing to learn but need to keep things as simple as possible.
I've tried reloading the page every 3 minutes using window.location.reload() but that doesn't work. I guess I could create a script to activate and focus the tab every few minutes, but that would interrupt anything I was working on. I tested it with the following barebones script against https://www.google.co.uk/, in case something else in my script was causing a problem, but the same happens:
var i = 0;
setInterval(function() {
console.log("log: i:" + i);
i = i+1;
if(i==15) {
i = 0;
window.location.reload();
console.log("reloaded window");
}
}, 10000);
After a few minutes, i is incremented only once per minute - even following the window reload.
I've looked at this question
It mentions "workers" but can these be used within tampermonkey on public website I don't own? It also provides a link which suggests a workaround of playing an almost inaudible audio file - but I don't know if playing that within my tampermonkey script would work?
I see there are a number of workarounds here but I'm not sure if I can use any of them.
For example, can MutationObserver be used within a tampermonkey to detect changes in a public website? Even if it can, presumably I'd have to reload the webpage every time I needed to checK? Currently I'm using XMLHttpRequest instead of loading the webpage (far quicker and uses less CPU).
Interestingly, the above link seems to suggest that setInterval and SetTimeout are specifically targetted for throttling, I wonder if that means I could use some other function instead.
I've also seen this but I guess I can only use that for a website I own?
I can think of a few options.
Instead of having three scripts, use a single script, and run that single script on every site (with // #match *://*/*). Then, with that single script, set the interval. Whenever the interval callback runs, use Tampermonkey's GM_setValue and GM_getValue for cross-domain storage to coordinate executions - a callback will first check with getValue whether the last check was more than 3 minutes ago. If so, it calls setValue with the current date and performs the check. This way, even if the script is running on 100 different tabs (some in active tabs, some in background tabs), it'll still run the check once every few minutes.
To perform the check, use Tampermonkey's GM_xmlHttpRequest to get across same-origin restrictions; make a request to the three sites, and parse them into documents using DOMParser so you can programatically search through them for the elements you're looking for.
Perform the checks from a backend app instead of from a browser - for example, with Node and Puppeteer, which won't have throttling issues. To have the results be communicated with you, you could either have a userscript or websocket with your local webserver, or you could integrate the webserver into an Electron app instead. This is the approach I'd prefer, I think it's the most robust.
Use workers, which has worked for some

Redux time travel debugging with current time dependency

In my application I have a selector that checks if the data it's fetching is stale. If it isn't stale, the selector returns the data; else it doesn't. It checks the staleness by comparing the current time (via new Date()) with the time that the data was loaded.
When trying to scrub back in forth in actions in the Redux dev tools, however, since the time is not part of the Redux store, the selector will call the data stale even if at the time of the action it wasn't.
So the core problem seems to be that Redux is no longer acting as a single source of truth—the clock time is now an external dependency. The goal, then, would be for the clock time when the selector is accessed to be a part of the Redux state, to properly allow for time travel debugging.
But what is the most elegant way to have an access of the Redux store dispatch a state transition? One way is to manually add an updateTime() dispatch every time you access the selector, but that requires remembering every time the selector is invoked to make that call, which I find to be less than ideal.
Another floated option was to keep track of the current time upon every state transition, but that doesn't help since it doesn't actually trigger an update upon time of access, but only upon the time that the state itself changed.
How do other people deal with this problem? I'm failing to find a nice solution around this. Thanks!

Execute function at future date/time even if website not in use?

Any ideas as to how I can set a function up so that it runs in a week's time whether or not the app is in use at that time? So far I have thought of using window.setTimeout but that is obviously dependent on the current browser session (to my understanding). I've also thought of a while loop but it seems like that would be a messy solution.
Any help would be welcome. Thank you.
As soon as the browser loads another page or closes (tab or entirely), your script is stopped and get's unloaded.
Thus, you are unable to leave a "time bomb" for in a week, unless the user let's the page linger in the browser for that time at least.
The only solution to dispatch an event on the client is to use a ServiceWorker and a push notification, but this is a very new and not widely adapter solution.

Syncing Database and Javascript

I'm working on a real-time JavaScript Application that requires all changes to a database are mirrored instantly in JavaScript and vise versa.
Right now, when changes are made in JavaScript, I make an ajax call to my API and make the corresponding changes to the DOM. On the server, the API handles the request and finishes up by sending a push using PubNub to the other current JavaScript users with the change that has been made. I also include a changeID that is sequential to JavaScript can resync the entire data set if it missed a push. Here is an example of that push:
{
"changeID":"2857693",
"type":"update",
"table":"users",
"where":{
"id":"32"
},
"set":{
"first_name":"Johnny",
"last_name":"Applesead"
}
}
When JavaScript gets this change, it updates the local storage and makes the corresponding DOM changes based on which table is being changed. Please keep in mind that my issue is not with updating the DOM, but with syncing the data from the database to JavaScript both quickly and seamlessly.
Going through this, I can't help but think that this is a terribly complicated solution to something that should be reasonably simple. Am I missing a Gotcha? How would you sync multiple JavaScript Clients with a MySQL Database seamlessly?
Just to update the question a few months later - I ended up sticking with this method and it works quite well.
I know this is an old question, but I've spent a lot of time working on this exact same problem although for a completely different context. I am creating a Phonegap App and it has to work offline and sync at a later point.
The big revelation for me is that what I really need is a version control between the browser and the server so that's what I made. stores data in sets and keys within those sets and versions all of those individually. When things go wrong there is a conflict resolution callback that you can use to resolve it.
I just put the project on GitHub, it's URL is https://github.com/forbesmyester/SyncIt

How can I have a JS script update a page for everyone viewing it?

I'm creating a web application that allows users to make changes through Javascript. There is not yet any AJAX involved, so those changes to the DOM are being made purely in the user's local browser.
But how can I make those DOM changes occur in the browser of anyone else who is viewing that page at the time? I assume AJAX would be involved here. Perhaps the page could just send the entire, JS-modified source code back to the server and then the other people viewing would receive very frequent AJAX updates?
Screen sharing would obviously be an easy work-around, but I'm interested to know if there's a better way, such as described above.
Thanks!
You are talking about comet, for an easy implementation i'd suggest:
http://www.ape-project.org/
and also check these:
http://meteorserver.org/
http://activemq.apache.org/ajax.html
http://cometdaily.com/maturity.html
and new html5 way of it
http://dev.w3.org/html5/websockets/
Hope these help.
Max,
Ajax will have to be involved. If i may, I'd like to suggest jQuery as a starting point for this (i know you didn't tag as such, but i feel it'd be appropriate, even if only to prototype with). the basic semantics would involve running the ajax request in combination with a setInterval() timer to fire off the ajax request. this could be done in jQuery along the lines of:
$(document).ready(function() {
// run the initial request
GetFreshInfo();
// set the query to run every 15 seconds
setInterval(GetFreshInfo, 1500);
});
function GetFreshInfo(){
// do the ajax get call here (could be a .net or php page etc)
$.get('mypageinfostuff.php', null, function(data){$('#myDivToUpdate').html(data);});
}
that's the basic premise... i.e the webpage is loaded via GetFreshInfo() initially straight away, then it's requeried every 15 seconds. you can add logoc to only refresh the div if there is new data there, rather than always updating the page. as it's ajax, the page won't freeze and the process will be almost invisible to the user (unless you want to flag the changes in any way)
Hope this helps
jim

Categories