javascript setInterval() load - javascript

I am trying to figure out what kind of load the window function setInterval() places on a user's computer. I would like to place a setInterval() on a page that is viewable only by my company's employees that will be checking a basic text file every 5 seconds or so and then if there is something to display, it will throw up some html code dynamically on the screen.
Any thoughts? Any better, less intrusive way to do this?

Appears it should not cause a problem, pending that the function setInterval() fires off is not heavy. Since I will only be reading a text file which should never be too large (text file will be overwritten about every minute by a completely separate job or bash script), the load should be minimal since it will be read in as a string, analyzed, and if necessary throw out a small amount of HTML code to the page.

I agree with all the comments regarding a single, polling setInterval() to be trivial.
However, if you want alternatives:
Long Polling
The browser makes an Ajax-style request to the server, which is kept
open until the server has new data to send to the browser, which is
sent to the browser in a complete response.
Also see:
PHP example and explanation
SignalR
Web Sockets
WebSockets is an advanced technology that makes it possible to open an
interactive communication session between the user's browser and a
server. With this API, you can send messages to a server and receive
event-driven responses without having to poll the server for a reply.

Related

Real Time Interaction on Web Page

Background: I have a microcontroller ESP8266 that enable connexion through TCP/IP, UDP or even HTTP stack using WiFi. A button is connected to this microcontroller and trigger event on touch. I send that information (now in UDP for test) towards a computer which runs an HTML carousel (web page). I would like to create the interaction between the button and the web page in real-time. I found that a simple HTML/CSS/JS web page doesn't allow to read UDP socket so I install a web server on the computer to use PHP.
NB: Real-time means direct interaction (inferior to 30 ms up to 100 ms) but should be ok in the actual data flow.
Problem: I struggle on the Web implementation. I found appropriate carousel in HTML/CSS/JS. I already received some UDP packet in a PHP file but I don't know how can I perform a real-time interaction (trigger image change in the carousel). I read about Ajax but it seems to be at client-side. I have in fact no background in Web application design.
I would like to know if in fact, it is possible and if yes basic information to start working on it.
Although I don't completely understand your microcontroller setup I can tell you that it is defiantly possible to change html elements and values in real-time. The place where I work uses Angular.js and it has a handy "scope" variable that is directly linked to the HTML. So, if the value in the code changes it will change on the website as well (without reloading the page). Its relatively simple to begin with but check out demos or something first, maybe I understand the question wrong.
https://angular.io/
Yes, this is definitely possible. Your two options are polling and websockets. If your backend is PHP, I'd start by writing some JavaScript to to poll the server at a given URL every 200 ms. Your PHP code handing that URL endpoint would then read a value from a data store somewhere, let's say a cache key in memcached.
Press button
UDP message sent
PHP code receives UDP message and sets value in cache key
When your polling code runs next it will receive the updated data which you can then display on your webpage.
This is a really basic (and inefficient) setup, but it's simple and should get you started.
We struggled with this same problem and eventually used NGINX and the PUSH module.
It allows a Post message to the server (NGINX) to be pushed to displayed web pages on the browser.
In our setup the controller sends a POST,containing JSON data, to a small linux board running NGINX. NGINX then sends this to any subscribers. The web page contains a couple of lines of js code to subscribe to the feed. When the JSON arrives at the page, it fires the js receiving code, and we update the displayed fields in the webpage. The setup is quite responsive, without measuring the delay, it seems to be within 60ms.

"Run and forget" a link from javascript

I'm working on a site that will keep a track of when user enters a page and how long he's there (or to be more specific, when he leaves)
I have set up a node server and I would like to run the action there, but the question is irrelevant to node itself, it's a javascript related question.
My goal is to have javascript call a certain method with specific parameters and then forget about that. However, I would like to avoid ajax if possible, I know I could do it with ajax, but I think that's an overkill and I'm not sure even if ajax would work on a node server.
What I'm looking at is something like
*User opens web page
*Javascript runs the script, let's say.
Run("http://server.com/User/EnteredPage/IDOFUSER");
and when the user closes the page
Run("http://server.com/User/LeftPage/IDOFUSER");
Point is.. I don't need anything from that call, I just want the javascript to run it, to save the data I need and that's it.
HTTP is stateless. The browser asks for a resource. The server gives the browser the resource. The end.
The request is done and dealt with. There is no further communication about that request so the server doesn't know when the visitor has left the page that it served up. If you want to know that, then you need another request to tell the server about it.
The problem with that approach is that the visitor might leave the page by:
Quitting their browser entirely
Running out of battery
Getting disconnected from the network
… so you can't reliably send a new request when the user leaves the page.
So the best you can do is to have the browser tell the server that the user hasn't left yet (you could do this with Ajax or (potentially more efficiently) WebSockets).
Combine this with a timer based action on the server that tests how long it has been since the visitor's browser last sent an I'm still here message and use that to call your visitor has left function.

stop iframe flickering when it refreshes

i have an iframe that loads my chatbox, but when it refreshed it flickers, how would I go about stopping it flickering. I have included the code below that I use to refresh the Iframe its self.
window.setInterval("reloadIFrame();", 2000);
function reloadIFrame() {
window.frames["chatlogs"].location.reload();
}
Thanks in advance for any help!
Not only might you want to use AJAX instead of an iframe, but depending on requirements you might also want to go look into using a server-side push. The problem being solved is, how does a client update its content when an event occurs on the server? Chat is a classic example of this. You have several options available to you, which I list below.
Frequent polling
The simplest solution. Each client repeatedly asks the server if there are any updates and is the closest to your iframe implementation. The downside comes from wasted bandwidth from communication overhead of each client request.
Long polling / Comet
when where the server keeps the clients waiting for a longer time (i.e. 5 sec) before returning as soon as an update occurs or timeout, whichever is sooner. With Comet, the server needs to be coded to keep client connections open without keeping any server threads waiting (otherwise the server will run out of threads to serve new requests and it'll be a performance nightmare).
WebSockets
New in HTML 5, WebSockets support bidirectional communication between client and server and are the recommended technology for any communication for server-side push.
You can find a good example with WebSockets here, which, guess what? Happens to be a guy trying to implement a chat application :)
Misc
For the record, you'll be able to eliminate iframe flicker if instead of keeping one iframe and refreshing it, your JavaScript creates a new hidden iframe with the same URL and position as the old one, and when it loads make it visible and delete the old iframe.

Prevent recursive calls of XmlHttpRequest to server

I've been googling for hours for this issue, but did not find any solution.
I am currently working on this app, built on Meteor.
Now the scenario is, after the website is opened and all the assets have been loaded in browser, the browser constantly makes recursive xhr calls to server. These calls are made at the regular interval of 25 seconds.
This can be seen in the Network tab of browser console. See the Pending request of the last row in image.
I can't figure out from where it originates, and why it is invoked automatically even when the user is idle.
Now the question is, How can I disable these automatic requests? I want to invoke the requests manually, i.e. when the menu item is selected, etc.
Any help will be appriciated.
[UPDATE]
In response to the Jan Dvorak's comment:
When I type "e" in the search box, the the list of events which has name starting with letter "e" will be displayed.
The request goes with all valid parameters and the Payload like this:
["{\"msg\":\"sub\",\"id\":\"8ef5e419-c422-429a-907e-38b6e669a493\",\"name\":\"event_Coll_Search_by_PromoterName\",\"params\":[\"e\"]}"]
And this is the response, which is valid.
a["{\"msg\":\"data\",\"subs\":[\"8ef5e419-c422-429a-907e-38b6e669a493\"]}"]
The code for this action is posted here
But in the case of automatic recursive requests, the request goes without the payload and the response is just a letter "h", which is strange. Isn't it? How can I get rid of this.?
Meteor has a feature called
Live page updates.
Just write your templates. They automatically update when data in the database changes. No more boilerplate redraw code to write. Supports any templating language.
To support this feature, Meteor needs to do some server-client communication behind the scenes.
Traditionally, HTTP was created to fetch dead data. The client tells the server it needs something, and it gets something. There is no way for the server to tell the client it needs something. Later, it became needed to push some data to the client. Several alternatives came to existence:
polling:
The client makes periodic requests to the server. The server responds with new data or says "no data" immediately. It's easy to implement and doesn't use much resources. However, it's not exactly live. It can be used for a news ticker but it's not exactly good for a chat application.
If you increase the polling frequency, you improve the update rate, but the resource usage grows with the polling frequency, not with the data transfer rate. HTTP requests are not exactly cheap. One request per second from multiple clients at the same time could really hurt the server.
hanging requests:
The client makes a request to the server. If the server has data, it sends them. If the server doesn't have data, it doesn't respond until it does. The changes are picked up immediately, no data is transferred when it doesn't need to be. It does have a few drawbacks, though:
If a web proxy sees that the server is silent, it eventually cuts off the connection. This means that even if there is no data to send, the server needs to send a keep-alive response anyways to make the proxies (and the web browser) happy.
Hanging requests don't use up (much) bandwidth, but they do take up memory. Nowadays' servers can handle multiple concurrent TCP connections, so it's less of an issue than it was before. What does need to be considered is the amount of memory associated with the threads holding on to these requests - especially when the connections are tied to specific threads serving them.
Browsers have hard limits on the number of concurrent requests per domain and in total. Again, this is less of a concern now than it was before. Thus, it seems like a good idea to have one hanging request per session only.
Managing hanging requests feels kinda manual as you have to make a new request after each response. A TCP handshake takes some time as well, but we can live with a 300ms (at worst) refractory period.
Chunked response:
The client creates a hidden iFrame with a source corresponding to the data stream. The server responds with an HTTP response header immediately and leaves the connection open. To send a message, the server wraps it in a pair of <script></script> tags that the browser executes when it receives the closing tag. The upside is that there's no connection reopening but there is more overhead with each message. Moreover, this requires a callback in the global scope that the response calls.
Also, this cannot be used with cross-domain requests as cross-domain iFrame communication presents its own set of problems. The need to trust the server is also a challenge here.
Web Sockets:
These start as a normal HTTP connection but they don't actually follow the HTTP protocol later on. From the programming point of view, things are as simple as they can be. The API is a classic open/callback style on the client side and the server just pushes messages into an open socket. No need to reopen anything after each message.
There still needs to be an open connection, but it's not really an issue here with the browser limits out of the way. The browser knows the connection is going to be open for a while, so it doesn't need to apply the same limits as to normal requests.
These seem like the ideal solution, but there is one major issue: IE<10 doesn't know them. As long as IE8 is alive, web sockets cannot be relied upon. Also, the native Android browser and Opera mini are out as well (ref.).
Still, web sockets seem to be the way to go once IE8 (and IE9) finally dies.
What you see are hanging requests with the timeout of 25 seconds that are used to implement the live update feature. As I already said, the keep-alive message ("h") is used so that the browser doesn't think it's not going to get a response. "h" simply means "nothing happens".
Chrome supports web sockets, so Meteor could have used them with a fallback to long requests, but, frankly, hanging requests are not at all bad once you've got them implemented (sure, the browser connection limit still applies).

Quick AJAX responses from Rails application

I have a need to send alerts to a web-based monitoring system written in RoR. The brute force solution is to frequently poll a lightweight controller with javascript. Naturally, the downside is that in order to get a tight response time on the alerts, I'd have to poll very frequently (every 5 seconds).
One idea I had was to have the AJAX-originated polling thread sleep on the server side until an alert arrived on the server. The server would then wake up the sleeping thread and get a response back to the web client that would be shown immediately. This would have allowed me to cut the polling interval down to once every 30 seconds or every minute while improving the time it took to alert the user.
One thing I didn't count on was that mongrel/rails doesn't launch a thread per web request as I had expected it to. That means that other incoming web requests block until the first thread's sleep times out.
I've tried tinkering around with calling "config.threadsafe!" in my configuration, but that doesn't seem to change the behavior to a thread per request model. Plus, it appears that running with config.threadsafe! is a risky proposition that could require a great deal more testing and rework on my existing application.
Any thoughts on the approach I took or better ways to go about getting the response times I'm looking for without the need to deluge the server with requests?
You could use Rails Metal to improve the controller performance or maybe even separate it out entirely into a Sinatra application (Sinatra can handle some serious request throughput).
Another idea is to look into a push solution using Juggernaut or similar.
One approach you could consider is to have (some or all of) your requests create deferred monitoring jobs in an external queue which would in turn periodically notify the monitoring application.
What you need is Juggernaut which is a Rails plugin that allows your app to initiate a connection and push data to the client. In other words your app can have a real time connection to the server with the advantage of instant updates.

Categories

Resources