Last active
August 29, 2015 14:19
-
-
Save think2011/807cfca2a0d0d89e9dca to your computer and use it in GitHub Desktop.
PollAjax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 轮询ajax请求 | |
* @param fn | |
* @param [delay = 500] | |
* @constructor | |
* @example | |
* var pa = new PollAjax(function (continueNext, done) { | |
$.get('../') | |
.done(function (data) { | |
if (data.success) { | |
done(); | |
} | |
}) | |
.always(function () { | |
continueNext(); | |
}); | |
}, 1000); | |
pa.start(5, cb); | |
pa.always(cb); | |
*/ | |
function PollAjax (fn, delay) { | |
this.finish = false; | |
this.progress = false; | |
this.delay = delay || 500; | |
this.fns = []; | |
this.fn = fn; | |
} | |
/** | |
* 次数 | |
* @param time | |
* @param cb 完成后的回调 | |
*/ | |
PollAjax.prototype.start = function (time, cb) { | |
var that = this; | |
for (var i = 0; i < time; i++) { | |
that.fns.push(that.fn); | |
} | |
that.next(); | |
that.cb = cb; | |
}; | |
/** | |
* 手动触发的完成 | |
*/ | |
PollAjax.prototype.done = function () { | |
this.progress = false; | |
this.finish = true; | |
this.fns = []; | |
if(this.cb) this.cb(); | |
}; | |
/** | |
* 继续下一个fn | |
*/ | |
PollAjax.prototype.continueNext = function () { | |
var that = this; | |
that.progress = false; | |
if(that.fns.length) { | |
that.next(); | |
} else { | |
if(that.alwaysCB) that.alwaysCB(); | |
} | |
}; | |
/** | |
* 队列结束时的回调 | |
* @param [cb] | |
*/ | |
PollAjax.prototype.always = function (cb) { | |
this.alwaysCB = cb; | |
}; | |
/** | |
* 执行下一个fn | |
*/ | |
PollAjax.prototype.next = function () { | |
var that = this; | |
if(!that.progress & !that.finish && that.fns.length != 0) { | |
that.progress = true; | |
setTimeout(function () { | |
(that.fns.pop())(that.continueNext.bind(that),that.done.bind(that)); | |
}, that.delay); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment