Hi all I have this working method to call an array of functions at recurring intervals.
Here you can see the object with the methods to add/remove functions in the array and the functions to start/stop the calling interval. (You have to focus only to the start method but I put them all for clarification)
function updateEngine() {
var _callRecurringFunctions = null,
_functionsToCall = [],
_functionIds = [],
_functionApps = [];
updateEngine.prototype.addFunction = function (appCode, funcId, func) {
if ($.isFunction(func) &&
$.inArray('_' + appCode + '_' + funcId, _functionIds) == -1) {
_functionApps.push(appCode);
_functionIds.push('_' + appCode + '_' + funcId);
_functionsToCall.push(func);
}
}
updateEngine.prototype.removeFunction = function (appCode, funcId) {
if (funcId == null) { // remove all functions relative to an app
for (var x = 0; x < _functionApps.length; x++) {
if (_functionApps[x] == appCode) {
_functionApps.splice(x, 1);
_functionIds.splice(x, 1);
_functionsToCall.splice(x, 1);
}
}
}
else { // remove the single app function
var pos = $.inArray('_' + appCode + '_' + funcId, _functionIds);
if (pos >= 0) {
_functionApps.splice(pos, 1);
_functionIds.splice(pos, 1);
_functionsToCall.splice(pos, 1);
}
}
}
updateEngine.prototype.start = function () {
_callRecurringFunctions = setInterval(function () {
for (var x = 0; x < _functionsToCall.length; x++) {
var frame = null;
// id == -1: local function
// id == 0: function defined in home iframe
// id > 0: function defined in an app iframe
if (_functionApps[x] >= 0)
frame = _portalContent.find("iframe[id='" + _functionApps[x] + "']");
if (frame != null && frame.get(0) != null) {
var iframeContent = frame.get(0).contentWindow || frame.get(0).contentDocument;
_functionsToCall[x].apply(iframeContent);
}
else
_functionsToCall[x]();
}
}, _updateFrequence); // tick every 5 seconds
}
updateEngine.prototype.stop = function () {
clearInterval(_callRecurringFunctions);
_callRecurringFunctions = null;
_functionApps = [];
_functionIds = [];
_functionsToCall = [];
}
}
I want to convert the start
method using setTimeout
instead of setInterval
and I wrote something like this:
updateEngine.prototype.start = function () {
function doLoop() {
$.when.apply($, _functionsToCall)
.done(function() {
setTimeout(doLoop, _updateFrequence);
});
}
setTimeout(doLoop, _updateFrequence);
}
How can I change the context of the array functions _functionsToCall
like I do in the previous method to pass the iframe context to each function?