Cancel Javascript timeout - javascript

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.

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.

What happens to setTimeout when the window is out of focus?

I have a situation where I need to reauthenticate a token on a cordova app before the authentication token expires. To do that I figured I'd set a timeout just before the auth token expires, to reauthenticate.
function authenticate() {
var token = ... get token
setTimeout(function() {
.. try to reauthenticate
}, token.expiresIn - 600*1000);
}
Problem I could see is that-
The timeout period passes while the app is sleeping. Function does not fire?
The timeout "countdown" (if that's how it works) is paused while the app is sleeping.
Neither of these are good scenarios. So my question is, what happens to a timeout while the application is out of focus? Should I instead have a 10 second interval that checks the expiration for this scenario?
Edit:
So lets say the token is for 4 hours. If the user uses the app for an hour, minimizes it for 2 hours and comes back, will the function call in an hour or 3 hours? This would be the point of the interval, so I can check the situation relatively quickly.
The timeout behavior really depends on the device type and OS version. On some, any timers that are "due" fire as soon as the application becomes active. On others (and I believe this is the case for current iOS), the timer is paused while your application is inactive and resumes when it becomes active.
For a long-running timer (i.e. your 4 hours example) you can't rely on the setTimeout() because on some devices it won't account for the inactive time. You'll need to subscribe to Cordova's resume event and re-calculate and update your timers. The following setLongTimeout() function should behave as expected in Cordoval. It's untested and would need to be expanded if you need multiple long timeouts.
var longTimeoutId, longTimeoutDate, longTimeoutCallback;
// Use instead of `setTimeout()` for a long timeout in Cordova
function setLongTimeout(callback, delay) {
if (longTimeoutId) {
clearTimeout(longTimeoutId);
}
longTimeoutCallback = callback;
longTimeoutDate = Date.now() + delay;
longTimeoutId = setTimeout(function() {
longTimeoutId = null;
callback();
}, delay);
}
document.addEventListener("deviceready", function() {
document.addEventListener("resume", function() {
if (longTimeoutId) {
setLongTimeout(callback, longTimeoutDate - Date.now();
}
});
});

Recall Long Polling AJAX Request When it Fails/Network offline

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.

Timer display using Javascript/Jquery

I'm working on a thick client application which uses JavaScript and jQuery. My Session times out if it's left idle for 45 seconds or more (depending on different business/user).
Currently the timeout event is triggered by the vendor code to which I do not have access. I would like to display a timer on the screen if the session is found to be idle beyond a specific time threshold (for example: 25 seconds).
At the same time the timer should also match (marginal diff can be managed) with the third party timer (to which I do not have access).
Can someone suggest the best solution for this?
It's worth sharing any code you already have so that we can offer more precise advise for you.
However, to give you some pointers, take a look at the JavaScript window.setTimeout() method. It essentially triggers a callback after a set period of time. It's fairly safe to say that if your vendor is using JavaScript to keep track of time, then this is the same basic method they will be using too.
You can set and reset a timeout very easily so once set, you could listen for user interaction events (scrolling, clicking, etc) and use these to trigger a reset on the timeout (putting the 'count down' back to the start).
Do a bit of research, I'm sure you'll be able to develop a suitable solution!
With regards to interfacing with your vendor's timeout, without much more information none of us will be able to help. It doesn't sound like you have any control over this so it may not be possible (perhaps contact the vendor and ask?).
If you know what the timeout limits are for each use-case, you could ensure that your timeouts match theirs. However, this would be a little bit annoying given it's code-repetition and would also mean your application would 'break' if your vendor changes their timings.
TL/DR: Read into the JavaScript window.setTimeout() method if you want to write something that will do what you describe. However, the weak link will be that you don't have access to your vendor's timeout routines. With that in mind, my first step would be to contact the vendor and ask, they may have something in their API already available that you're unaware of!
Okay I don't quite get your logic, but a simple search on Google for jQuery plugin timer gives me:
http://www.tripwiremagazine.com/2013/04/jquery-countdown-scripts.html
A lot...
Hope one of them suits your needs.
Halo,
I finally managed to try a timer in my application (touch based). The following code works well for me.
var count = 50;
$(document).ready(function () {
var Timer = $.timer(function() {
$('#counter').html("Your Session will expire in " + --count + "seconds");
});
Timer.set({ time : 1000, autostart : true });
$(this).mousemove(function (e) {
idleTime = 0;
count = 50;
Timer.reset();
Timer.stop();
});
$(this).keypress(function (e) {
idleTime = 0;
count = 50;
Timer.stop();
Timer.reset();
});
var idleInterval = setInterval(function (){
idleTime = idleTime + 1;
if (idleTime > 10)
{
Timer.set({ time : 600, autostart : true });
$('#counter').css("display", "block");

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