Recall Long Polling AJAX Request When it Fails/Network offline - javascript

I am implementing a successful long polling within PHP/Node.js application. I have created a routine to launch the long polling AJAX request after the waking up of the computer (after sleep mode) as below.
The problem is that the AJAX request fails due to internet connectivity as it needs some time to get ready and this leads AJAX request to fail. I need to recall this request again until the internet is back but I can't find any way to know if the previous request has failed to send new one and track its status.
I am not using the Jquery and I don't want to use it.
I am able to create a timeout for direct AJAX calls if they don't reach a server within a timeout seconds, but the long polling request status is pending at server for 40 seconds and I need to detect if it fails after 2 seconds from sending.
Is there any solution to do with xmlHTTP object?
I would greatly appreciate your help. Thanks.
var program ={
init: function(){
this.isSleep = function(lastTime){
var lastTime = lastTime;
clearTimeout(program.tt)
program.tt = setTimeout(function(){
var currentTime = new Date().getTime();
if(currentTime > (lastTime + 2000*2) ){
// request fails if the internet connection was not ready
ajax.call({ // long polling request......});
}
program.isSleep(new Date().getTime());
}, 2000);
};
this.isSleep(new Date().getTime());
}
}

Set a variable to true, then call a timer for 2 seconds. If the ajax returns turn that variable to false, if the timer is fired then check your variable and do whatever you need to do.

Related

ERR_INSUFFICIENT_RESOURCES ajax code for REAL-TIME CLOCK

I created a real-time clock that updates every second. When I run it locally I see no errors. However when I uploaded it to my web host I saw a lot of error messages in the console every time the AJAX code runs.
I think that's the reason why web host suspended my site, telling that my site has performed too many requests.
Here is my code:
$(document).ready(function() {
setInterval(function() {
$('#time').load('timewithdate.php')
}, 1000);
setInterval(function(){
$('#time2').load('time.php')
}, 1000);
})
I'm not sure what kind of answer you are looking for. Your code is a certain way to kill a server: it's making 2 calls to the server every second for each client (read more about DDOS). There is no need to make a server call, just use javascript to get the current time and format it the way you want. You can have something like this:
$(document).ready(function() {
setInterval(function() {
let curTime = new Date();
let date = curTime.toLocaleDateString();
let time = curTime.toLocaleTimeString();
$('#time').text(date + " " + time);
$('#time2').text(time);
}, 1000);
})
The error is because you have effectively DDOS'd your own server with 2 requests every second * number of concurrent clients. I would strongly suggest you remove these AJAX requests and perform the countdown on the client side.
If you're trying to keep the clocks in sync with server time, get the time from the server when the page loads, then add seconds to it on the client side. Do not use AJAX for this, and do not use AJAX polling in future. It's an anti-pattern.

Excel for Mac JS Add-in HTTP Request Timeout

I'm working on an Excel js add-in. The add-in has multiple rest api calls using ajax. One in particular can take some time to respond (in this case over 10 minutes). It is working properly in Excel Online - the response is received and displayed. Excel for Mac appears to have a timeout (or something) affecting the request after 1 minute. It's returning a status code 0 and our server is throwing a 499 (client cancelled request).
Is there a timeout in Office for Mac and, if so, is there a way to change it? Adding a timeout field to the ajax request isn't working.
I think this is the same question as Lengthy HTTP calls failing in TaskPane apps on Office for Mac Client. There is a default timeout of 60 seconds for the WebKit control Office uses. There is no way to override the default timeout from our end. I have tried the following code that works with a 10 minute request:
var xhr = new XMLHttpRequest();
var startDate = new Date();
xhr.open('POST', url, true);
xhr.timeout = 800000; // time in milliseconds
xhr.onload = function () {
console.log((new Date() - startDate) + " milliseconds to return.");
};
xhr.ontimeout = function (e) {
console.error("error");
};
xhr.send("data");
Note that there was a WebKit regression that is now fixed that broke setting the timeout property. You will need the latest version of Safari. Also, jQuery timeout property wasn't working because they are not actually setting the native XMLHttpRequest::timeout property that WebKit listens to. If you are using a third party library to make the request, make sure it sets XMLHttpRequest timeout properly.

Determine if a websocket send() is finished

Is there a way to get notified if a certain send() has finished? As i noticed the send() function is not blocking and the code continuous. Is there a simple way to either make it blocking or getting somehow notified if the send is finished?
You could rely on Socket.bufferedamount (never tried)
http://www.whatwg.org/specs/web-apps/current-work/multipage/network.html#dom-websocket-bufferedamount
var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0){
// Im' not busy anymore - set a flag or something like that
}
}, 50);
};
Or implement an acknowledge answer from the server for every client message (tried, works fine)

Cancel Javascript timeout

I have a long process hosted on a Web Server. The thing is triggered from a Web Page, at the click of a button by a user. Some Javascript polls regularly via Ajax to check if the operation has completed server side. To do this, I use setInterval, and later on clearInterval to stop polling.
If this takes too long (e.g. server has crashed), I'd like the client to be informed by some sort of timeout. I've done some research and found about setTimeout. Problem is, if the operation finishes successfully before the timeout, I'd like to cancel this one.
How to do this ?
Would you suggest a different approach ?
PS : I'm targetting IE7/IE8 in particular, but always open to some JQuery
As long as you store your interval's id in a variable, you can use it to clear the interval at any time.
var interval = window.setInterval(yourFunction, 10000);
...elsewhere...
window.clearTimeout(interval);
For more information see the Mozilla Documentation's setInterval example.
Put together a quick JS Fiddle containing a modified version of Mozilla's Example.
To clear a setTimeout, use clearTimeout.
You want two timers (as you said)
repeating interval to do the next poll and
one-time expiration to give up if the server never responds
If the polling is successful you want to clear both the polling interval and cancel the failure timer. If the expiration timer fires you want to clear the polling interval
var checkCount = 0;
function checkComplete() {
console.log("test " + checkCount);
if (checkCount++ > 10) {
console.log("clearing timeout");
window.clearInterval(pollInterval);
window.clearTimeout(expireTimer);
}
}
function cancelPolling(timer) {
console.log("clearing poll interval");
window.clearInterval(pollInterval);
}
var pollInterval = window.setInterval(checkComplete, 500);
var expireTimer = window.setTimeout(cancelPolling, 10000);
You can fiddle with the checkCount constant "10" - keep it low to simulate polling success, raise it higher for the timeout to occur before the checkCount is reached, simulating polling failure.

How to have a timer which cannot be modified in javascript?

Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());

Categories

Resources