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();
});
Your parentheses there will automatically run
methods.request, which in turn will run code that automatically runsmethods.requeston down the line; basically, the method will execute over and over again, binding increasingly more versions of itself to your interval.That’s what you’re looking for: just passing the function signature instead of passing a function that executes as a side-effect.