Do javascript timers impact bandwidth - javascript

I have a page that uses a few timers and ajax calls to make it dynamic ie if i change anything on my ipad the page updates on my laptop ..and it querys a database and updates...
will this have an impact on my bandwidth because it constantly updates? anything to be worried about?

Each AJAX call will create a connection to the server (unless an existing keep-alive connection is re-used) and send a HTTP request. This is extremely small though so it will not affect your network performance in a noticeable way.
However, for this kind of real-time notification polling is a bad idea. All somewhat modern browsers support WebSockets nowadays which use one persistent connection to transmit data.

Using a few timers and AJAX calls will impact the bandwidth, more so if you're on an iPad / iPhone somewhere using your prepaid Internet minutes on a SIM card etc.
The amount of impact it will create is, however dependent on the frequency and the actual response. You have the following options to make it as painless as possible (bandwidth-wise):
minimize the AJAX response size - make it as small as possible if nothing changes, ideally completely empty
stop making AJAX calls when application is in the background - on IOS, it's possible to tell when the app is on a background, so if you don't need visual updates at that time but the app is still running, simply stop requesting them.
if you do need to be notified with the app on background, you are best to use Push notifications (as the app can get killed, paused, suspended while in the background)
as pointed out in the previous comments, you can use long polling to replicate Push notifications as well
Hope this helps ;-)

Related

Bidirectional server/client communication in JavaScript and PHP

I want to create a multiplayer game using JavaScript (no jQuery) and PHP, where most of the mechanics use AJAX calls. However, I need to determine when a user has left the game to update the player status on other players' screens (I assume by regular AJAX requests?). Also, once all players have left the game files (.txts) on the server need to be deleted.
I am using a free web hosting service which means I can't use WebSockets or cron jobs. I also don't want to use Node.js. Most of what I have read advise regularly timestamping with PHP sessions and this is fine, but I would like to know how to then check to see if the user/game has been inactive for a period of time.
Also, using window.onbeforeunload is too unreliable, in case browsers crash etc.
Don't use the wrong tool for the job.
Any kind of AJAX-based solution you attempt for this purpose is likely to very be inefficient, or unreliable, or probably both. If you have more than a tiny number of concurrent users, the sheer volume of AJAX requests would be likely to overwhelm the server and potentially bust your monthly quota. And as you've discovered, determining when someone has ended their session by closing the browser window is not straightforward or reliable. I would advise against any such architecture.
Websockets is really the correct solution for real-time or near-real-time updates between client and server (and vice versa). It'a also easy for the socket server to know when someone has disconnected (which would occur if they close the window/tab).
So you could either upgrade your hosting so you're able to run a websocket server successfully, or try to integrate a websocket based solution hosted elsewhere, e.g. Azure SignalR or some similar product (I am not making specific recommendations in an answer, as that's regarded as off-topic).
use an interval function and ping the php endpoint every second.
If it stops the User is out

Is it ok to send xmlhttprequest to a server every second?

I am creating a Chrome extension that checks gmail inbox.
I'm using the xml feed url to fetch it:
https://mail.google.com/mail/u/0/feed/atom
For updating, I'm using chrome.alarms API that sends GET request every 10 seconds. Is that too much? If not, could I change it to 1 second too? How much load does their server have to handle in order to send me the feed's information?
Using XHR every 10 seconds looks like not bad idea, but every second might be too much. Each XHR request creates new connection, sending lots of data to server, and lots of data will receive. If you need a real-time app, please consider to using Websocket or Socket.io instead. They are very lightweight, fast and easy to use.
Notification APIs (gmail seems to have them)
You can get updates with a lot less latency if you use a different technique such as "long polling" or "web sockets". This is very useful for things where you want no lag, like a real-time chat, a web-based video game, or a time-sensitive process like an auction or ticket/order queue. It might be a bit less important for something less real-time, like email (see the last paragraph in this answer).
Gmail seems to have an API that is explicitly designed for fast notifications.
HTTP polling
Most web servers can stand up to being called once a second without killing their site. If they can't, then they have some serious security problems (Denial of Service attacks, or worse if their site is buggy enough to suffer data loss when overloaded).
Google has big servers, and protection, so you don't really need to worry about what they can handle, as long as they don't block you. Google may rate limit calls to their gmail API, and you may end up getting a user throttled if you call their API more then they prefer. Consult their documentation to find out what their rate limiting policies are.
To more generically answer you question, normal HTTP isn't really optimized for frequent polling for refreshed data. You can make a decent number of requests (even upwards of one a second or more). You probably won't kill the computer or browser or even make them run slowly, as long as the request and response payload data is small enough, and the processing/dom changes you do with the response are minimal when the data comes back unchanged.
Assuming you don't violate per-site rate limits, and have small data payloads in the request you are making, then the biggest problem is that you might still be wasting a lot of bandwidth. For people who have to pay by the minute/megabyte, this is a problem. This is much more frequent in Europe than in the United States (although it is also frequent on cellular devices).
Consider if you really need email to be checked every second. Would every ten seconds be fine? Maybe every minute? Maybe your app could do a refresh when you send mail, but take longer to check for new mail when it is idle? Think about what use cases you are solving for before assuming everything always has to be constantly updated. What would waiting a few extra seconds break? If the answer is nothing, then you can safely slow down your updates. If there are use cases that would be broken or annoying, then figure out why it is important. See if there are even better ways to address that use case, or if updating frequently is actually the right answer. Sometimes it is!

Prevent Service Worker from automatically stopping

Service Worker seems to automatically stop at some point. This behaviour unintentionally closes the WebSocket connection established on activate.
When and Why does it stop? How can I programmatically disable this unexpected action to keep Service Worker stay running?
What you're seeing is the expected behavior, and it's not likely to change.
Service workers intentionally have very short lifespans. They are "born" in response to a specific event (install, activate, message, fetch, push, etc.), perform their task, and then "die" shortly thereafter. The lifespan is normally long enough that multiple events might be handled (i.e. an install might be followed by an activate followed by a fetch) before the worker dies, but it will die eventually. This is why it's very important not to rely on any global state in your scripts, and to bootstrap any state information you need via IndexedDB or the Cache Storage API when your service worker starts up.
Service workers are effectively background processes that get installed whenever you visit certain web pages. If those background processes were allowed to run indefinitely, there's an increased risk of negative impact on battery and performance of your device/computer. To mitigate this risk, your browser will only run those processes when it knows it's necessary, i.e. in response to an event.
A use case for WebSockets is having your client listen for some data from the server. For that use case, the service worker-friendly alternative to using WebSockets is to use the Push Messaging API and have your service worker respond to push events. Note that in the current Chrome implementation, you must show a user-visible notification when handling a push event. The "silent" push use case is not supported right now.
If instead of listening to data from the server, you were using WebSockets as a way of sending data from your client to your server, there's unfortunately no great service worker-friendly way of doing that. At some point in the future, there may be a way of registering your service worker to be woken up via a periodic/time-based event at which point your could use fetch() to send data to the server, but that's currently not supported in any browsers.
P.S.: Chrome (normally) won't kill a service worker while you have its DevTools interface open, but this is only to ease debugging and is not behavior you should rely on for a real application.
The Theory
Jeff's answer explains the theory part - why and how, in detail.
It also includes many good points on why you might not want to pursue this.
However, in my case, the downsides are nonexistent since my app will run on desktop machines which are reserved only to run my app. But I needed to keep the SW alive even when the browser window is minimized. So, if you are working on a web app which will run on variety of devices, keeping the SW alive might not be a good idea, for the things discussed in above answer.
With that said, let's move onto the actual, practical answer.
My "Practical" Solution
There should be many ways to keep the SW alive, since SWs stay alive a bit after responding to many different events. In my case, I've put a dummy file to server, cached it in the SW, and requested that file periodically from the document.
Therefore the steps are;
create a dummy file on the server, say ping.txt
cache the file on your SW
request that file from your html periodically to keep the SW alive
Example
// in index.html
setInterval(function(){
fetch('/ping.txt')
}, 20000)
The request will not actually hit the server, since it will be cached on the SW. Nonetheless, that will keep the SW alive, since it will respond to the fetch even evoked by the request.
PS: I've found 20 seconds to be a good interval to keep the SW alive, but it might change for you, you should experiment and see.

'Web' based push notifications for internal-only application

I'm already tossing around a solution but as I haven't done something like this before I wanted to check what SO thought before implementation.
Basically I need to modify an existing web based application that has approximately 20 users to add push notifications. It is important that the users get the notifications at the same time (PC-A shouldn't get an alert 20 seconds before PC-B). Currently the system works off of AJAX requests, sending to the server every 20 seconds and requesting any updates and completely rebuilding the table of data each time (even if data hasn't changed). This seems really sloppy so there's two methods I've come up with.
Don't break the connection from server-client. This idea I'm tossing around involves keeping the connection between server and client active the entire time. Bandwidth isn't really an issue with any solution as this is in an internal network for only approximately 20 people. With this solution the server could push Javascript to the client whenever there's an update and modify the table of data accordingly. Again, it's very important that every connected PC receives the updates as close to the same time as possible. The main drawback to this is my experience, I've never done it before so I'm not sure how well it'd work or if it's just generally a bad idea.
Continue with the AJAX request, but only respond in intervals. A second solution I've thought of would be to allow the clients to make AJAX requests as per usual (currently every 20 seconds) but have the server only respond in 30 second intervals (eg 2:00:00 and 2:00:30 regardless of how many AJAX requests it recieves in that span of time). This would require adjusting the timeout for the AJAX request to prevent the request timing out, but it sounds okay in theory, at least to me.
This is for an internal network only, so bandwidth isn't the primary concern, more so that the notification is received as close to each other as possible. I'm open to other ideas, those are just the two that I have thought of so far.
Edit
Primarily looking for pros and cons of each approach. DashK has another interesting approach but I'm wondering if anyone has experience with any of these methods and can attest to the strengths and weaknesses of each approach, or possibly another method.
If I understand well your needs I think you should take a look to Comet
Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins.
The Comet approach differs from the original model of the web, in which a browser requests a complete web page at a time.
How about using an XMPP server to solve the problem?
Originally designed to be an Instant Messaging platform, XMPP is a messaging protocol that enables users in the system to exchange messages. (There's more to this - But let's keep it simple.)
Let's simplify the scenario a little bit. Imagine the following:
You're a system admin. When the system
has a problem, you need to let all the
employees, about 20 of them, know that
the system is down.
In the old days, every employee will
ask you, "Is the system up?" every
hour or so, and you'll response
passively. While this works, you are
overloaded - Not by fixing system
outage, but by 20 people asking for
system status every hour.
Now, AIM is invented! Since every
employee has access to AIM, you
thought, "Hey, how about having every
single one of them join a 'System
Status' chat room, and I'll just send
a message to the room when the system
is down (or is back)?" By doing so,
employees who are interested in
knowing system status will simply join
the 'System Status' room, and will be
notified of system status update.
Back to the problem we're trying to solve...
System admin = "System" who wants to notify the web app users.
Employees = Web app users who wants to receive notification.
System Status chat room = Still, system Status chat room
When web app user signs on to your web app, make the page automatically logs them onto the XMPP server, and join the system status chat room.
When system wants to notify the user, write code to logon to the XMPP server, join the chat room, and broadcast a message to the room.
By using XMPP, you don't have to worry about:
Setting up "Lasting connection" - Some open source XMPP server, eJabberd/OpenFire, has built-in support for BOSH, XMPP's implementation of the Comet model.
How the message is delivered
You however will need the following:
Find a Javascript library that can help you to logon to an XMPP server. (Just Google. There're a lot.)
Find a XMPP library for the server-side code. (XMPP library exists for both Java & C#. But I'm not sure what system you're using behind the scene.)
Manually provision each user on the XMPP server (Seems like you only have 20 people. That should be easy - However, if the group grows bigger, you may want to perform auto-provisioning - Which is achievable through client-side Javascript XMPP library.)
As far as long-lasting AJAX calls, this implementation is limited by the at-most-2-connection-to-the-same-domain issue. If you used up one connection for this XMPP call, you only have 1 more connection to perform other AJAX calls in the web-app. Depending on how complex your webapp is, this may or may not be desirable, since if 2 AJAX calls have already been made, any subsequent AJAX call will have to wait until one of the AJAX pipeline freed up, which may cause "slowness" on your app.
You can fix this by converting all AJAX calls into XMPP messages, and have a bot-like user on the server to listen to those messages, and response to it by, say, sending back HTML snippets/JSON objects with the data. This however might be too much for what you're trying to achieve.
Ahh. Hope this makes sense... or not. :p
See http://ajaxpatterns.org/HTTP_Streaming
It allows You to push data from the server when server wants it. Not just after the query.
You could use this technique without making large changes to the current application, and synchronize output by the time on the server.
In addition to the other two great options above, you could look at Web Workers if you know they have latest Chrome, Safari, FF, or Opera for a browser.
A Worker has the added benefit of not operating in the same thread as the rest of the page, so performance will be better. The downside is that, for security purposes, you can only send string data between the two scripts and the worker does not have window or document context. However, JSON can be represented as a string, so there's really no limit to the data.
Workers can receive data multiple times and asynchronously. You set the onmessage handler to act each time it receives something.
If you can ask every user to use a specific browser (Latest Safari or Chrome), you can try WebSockets too.

Rest / HTML - If server stops detect if server starts again?

Something I am playing with at the moment is a Rest / HTML page that dynamically updates via JSON calls.
Now in the case that I want this to run on as low a bandwidth as possible.
So if the server is shut down, then booted up again I want the updates to continue again in most cases this works some cases parts of the javascript won't work and it times out.
So what is a low overhead solution to detect that the Server has started up again?
(Looking for good ideas or other methods to do this)
thoughts:
So far I have thought of having a status request but this uses bandwidth again to continually run?
Or how to only run this status request once the server had gone down and stop when its up?
You could use the setInterval function to continuously poll the server for updates. Once a request fails you could enter a so called safe-mode by sending only HEAD requests (and as suggested by #sje397 also increase the timeout interval) to reduce bandwidth and once it succeeds you enter again normal mode and continue with GET/POST.
There are also more exotic things like COMET and Web Sockets in HTML 5 that allow the server to push updates to the client.

Categories