I made this little JavaScript poller. It doesn't use long polling. The reason is because I don't have much control over events that update the database it checks. So if I had used long polling I would have just done database polling on the server to update the long polling. But it does slow down the polling timer if the page is not used. You could alter it to take in an array of delays to use or even to generate the delays based on some function.
var PollingHandler = (function ($) {
var pollingDelays = [30, 30, 60, 60, 120, 120, 300, 300, 0]; // Values is seconds, Zero is a magic number meaning stop polling
var currentDelay = 0;
var arrayOfFunctions = [];
var timer;
var activateTimer = function () {
var plannedDelay = pollingDelays[currentDelay];
if (plannedDelay > 0) {
timer = setTimeout(function () {
for (var i = 0; i < arrayOfFunctions.length; i++) {
arrayOfFunctions[i]();
}
currentDelay++;
activateTimer();
}, plannedDelay * 1000);
}
};
var setup = function () {
$("body").mousemove(function () {
if (pollingDelays[currentDelay] === 0) {
currentDelay = 0;
activateTimer();
} else if (pollingDelays[currentDelay] > pollingDelays[0]) {
// if you are in a later gap and you get movement, don't wait for that gap to finish
// instead use smallest gap - this could theoretically increase your wait time till poll
clearTimeout(timer);
currentDelay = 0;
activateTimer();
} else {
currentDelay = 0;
}
});
activateTimer();
};
var addPolledFunction = function (functionToRun) {
arrayOfFunctions.push(functionToRun);
};
return {
Setup: setup,
AddListener: addPolledFunction
};
})(jQuery);
No comments:
Post a Comment