Skip to content

Instantly share code, notes, and snippets.

@JixunMoe JixunMoe/IntervalLoop.js
Last active Nov 26, 2018

Embed
What would you like to do?
Interval Loop (Loop array with delay & callback)
var IntervalLoop = function (arrData, looper, delay) {
if (!(this instanceof IntervalLoop))
return new IntervalLoop (arrData, looper, delay);
/**
* Status
* @type Number
* 0: 循环未开始
* 1: 正在循环
* 2: 循环结束
*/
this.status = 0;
this.next = this._next.bind (this);
this.index = 0;
this.setDelay (delay || 50);
this.data = (arrData instanceof Array) ? arrData : [];
this.setLooper (looper);
};
IntervalLoop.prototype = {
_getDelay: function () {
if (!this.delay)
return 50;
if (this.delay.apply)
return this.delay();
return this.delay;
},
_next: function () {
// 状态改为 进行中
this.status = 1;
if (this.index < this.data.length) {
setTimeout (this.looper.bind(this, this.data[this.index]), this.delay);
this.index ++;
} else {
this.status = 2;
}
},
cleanup: function () {
if (this.status == 2) {
// 已经用过的数据就清掉。
this.data.splice(0, this.index);
this.index = 0;
this.status = 0;
}
return this;
},
add: function () {
if (arguments.length > 0) {
// 将所有参数作为数据推入 this.data
for (var i = 0; i<arguments.length; i++)
this.data.push (arguments[i]);
// 整个组已经完结,清理后自动继续
if (this.status == 2)
this.cleanup().next();
}
// 连锁
return this;
},
setDelay: function (newDelay) {
if (newDelay) this.delay = parseInt (newDelay);
return this;
},
setLooper: function (fooCallback) {
if (fooCallback && fooCallback.apply)
this.looper = fooCallback.bind(this, this.next);
return this;
},
loop: function () {
if (this.status == 0)
// 尚未启动, 从头开始
this.next ();
return this;
}
};
// 用法:
var loop = new IntervalLoop ([1, 2, 3], function (next, item) {
$.ajax ({
url: 'http://example.com/?id=' + item
}).success (function (r) {
// TODO: 处理抓取的数据
// ...
next ();
});
}, 500).add (1, 2, 3).add (999).loop ();
// TODO: 监听节点更新
var xyz = document.addEventListener ('xyz', function (eve) {
// TODO: 解析数据并传递需要的值
loop.add(eve.target);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.