Keeping user session alive problem
I had an idea to keep my users' sessions alive by sending a webservice call, setting a timeout for a set amount of time (like 15 mins or so) then recall that same method.
Problem is the webservice appears to fire off continuously. Not every 15 mins like I thought.
A link can be found here: Fiddle
Code here:
(function($, window, document, undefined) {
"use strict";
var methods,
settings,
timeout,
type = 'sessionPing';
methods = {
init: function () {
settings = { time: 5000};
methods.request.call(this);
},
request: function () {
console.log('just before clear' + timeout);
clearTimeout(timeout);
$.ajax({ type: 'POST',
url: '/echo/html/',
data: {
'html': 'Echo!'
},
success: function(data) {
timeout = setTimeout(methods.request(), settings.time);
console.log('in success ' + timeout);
开发者_运维问答 },
dataType: 'html'
});
}
};
$.sessionPing = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.timeSince');
}
};
}(jQuery, window, document));
$(function() {
$.sessionPing();
});
timeout = setTimeout(methods.request(), settings.time);
Your parentheses there will automatically run methods.request
, which in turn will run code that automatically runs methods.request
on down the line; basically, the method will execute over and over again, binding increasingly more versions of itself to your interval.
timeout = setTimeout(methods.request, settings.time);
That's what you're looking for: just passing the function signature instead of passing a function that executes as a side-effect.
Fix the timeout so it calls a function:
timeout = setTimeout(function(){methods.request()}, settings.time);
If you do not do this, then the function that you had placed in the timeout will be called immediately.
Functions are first order objects in javascript. Inside your ajax success function you are setting a timeout:
timeout = setTimeout(methods.request(), settings.time);
However, note you are executing methods.request, not passing the function as an object for the timeout to execute. The correct code should be
timeout = setTimeout(methods.request, settings.time);
Note I've tested this on your fiddle and this updates fixes the problem.
You're setting your timeout to 5000 milliseconds, which means it will fire every 5 seconds, instead of the 15 minutes that you are looking for.
That would be 900000 milliseconds.
Use setInterval
instead of setTimeout
- it will be easier to manage and does precisely what you need.
精彩评论