var myTime = function() {
this.listOne = [];
this.listTow = [];
this.listThree = [];
this.timer = null;
// 同步
this.addAsynchro = function(fn, option) {
this.listOne.push({fn: fn, ...option});
return this;
}
// 同步
this.addAsynchroDelay = function(fn, option) {
this.listTow.push({fn: fn, ...option});
return this;
}
// 异步
this.addAsyncDelay = function(fn, option) {
this.listThree.push({fn: fn, ...option})
return this;
}
this.runAsynchro = function() {
const len = this.listOne.length;
if (len === 0) {
return;
}
let index = 0;
while(index < len) {
const fn =this.listOne[index].fn;
fn();
index ++;
}
}
this.stop = function(fn, millisecond) {
return new Promise((resolve) => {
this.timer = setTimeout(() => {
fn();
resolve();
}, millisecond)
})
}
this.runAsynchroDelay = function() {
const len = this.listTow.length;
if (len === 0) {
return;
}
let index = 0;
const doloop = (i) => {
const fn = this.listTow[i].fn;
let millisecond = 0;
let current = this.listTow[i];
if (current.offset && current.offset > 0) {
millisecond = current.offset;
current.offset = 0;
} else {
millisecond = current.millisecond;
}
this.stop(fn, millisecond)
.then(() => {
index ++;
if (index < len) {
doloop(index);
} else {
index = 0;
doloop(index);
}
})
}
doloop(0);
}
this.runAsyncDelay = function() {
const len = this.listThree.length;
if (len === 0) {
return;
}
let index = 0;
const loop = (fn, millisecond) => {
this.timer = setTimeout(() => {
fn();
loop(fn, millisecond);
}, millisecond);
}
for (let i = 0; i < len; i ++) {
loop(this.listThree[i].fn, this.listThree[i].millisecond);
}
}
this.run = function() {
this.runAsyncDelay();
this.runAsynchro();
this.runAsynchroDelay();
}
}
function a() {
console.log('a');
}
function b() {
console.log('b');
}
function c() {
console.log('c');
}
function d() {
console.log('d');
}
let times = new myTime();
// 1,可以为5秒后调用a,3秒后调用b,10秒后调用。c...z方法不执行(不执行的方法可以设计成不传递参数),那么在第14秒的时候开始重新从0秒循环,又变成第一秒后调用a,3秒后调用b,这样循环往复;
// times.addAsynchroDelay(a, { millisecond: 3000, offset: 5000}).addAsynchroDelay(b, { millisecond: 3000}).addAsynchroDelay(c, { millisecond: 14000})
// times.run();
// 2,每间隔6秒调用一次a,每间隔4秒调用一次b,c...z方法不执行;
// times.addAsyncDelay(a, { millisecond: 4000 }).addAsyncDelay(b, { millisecond: 4000 })
// times.run()
// 3,第一秒先执行a,3秒后执行b,但是c却是每间隔3秒执行一次,d是每间隔4秒执行一次,a和b是每4秒进行一次循环;
// times.addAsynchroDelay(a, { millisecond: 1000 }).addAsynchroDelay(b, { millisecond: 3000 }).addAsyncDelay(c, { millisecond: 3000 }).addAsyncDelay(d, { millisecond: 4000})
// times.run();
// 4,a不执行,b和c每间隔3秒执行一次,d不执行;
times.addAsyncDelay(b, { millisecond: 3000 }).addAsyncDelay(c, { millisecond: 3000 })
times.run();
console