when.js polling with jQuery promises
See when.js promises library https://github.com/cujojs/when
and the article
https://blog.visisoft.de/blog/2013/06/03/ajaxpolling/
HTML
<script src="http://requirejs.org/docs/release/2.1.5/comments/require.js"></script>
<button id="failWorker">Fail Worker</button>
<button id="cancelPolling">Cancel Polling</button>
helloooo
JavaScript
requirejs.config({
packages: [
{name: "when",
main: "when",
location: 'https://raw.github.com/cujojs/when/master/'}
]
});
setInterval(function(){ ajax_check_and_apply_updates_function(); }, 10000);
require(['when', 'when/poll'], function(when, poll){
var counter = 0;
var max_counter = 10;
var polling = poll(function(){
console.log("beginning work with " + counter);
var dfd = new $.Deferred();
setTimeout(function(){
if (counter < 2 * max_counter){
dfd.resolve(counter * counter);
}
else{
dfd.reject(counter);
}
}, 1000);
return dfd.promise();
}
, 2000
, function(result){
console.log("should finish for result:" + result);
return counter++ > max_counter;
});
$('#failWorker').on('click', function(){ counter = counter * max_counter; });
$('#cancelPolling').on('click', function(){ polling.cancel(); });
polling.then(console.log.bind(console, "DONE")
, console.log.bind(console, "FAIL")
, console.log.bind(console, "PROGRESS"));
});