-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
108 lines (96 loc) · 3.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const mapOrSingle = function(obj, fn){
if(obj.constructor !== Array){
return fn(obj);
}
else{
return obj.map(fn);
}
};
const createTimer = function(cron){
this._cron = this._cron || {};
const method = cron.method;
if(this._cron[method] && this._cron[method].timerRunning) return;
if(cron.autoStart === false){
this._cron[method] = { timerRunning: false };
}
else{
this._cron[method] = {
timer: setInterval(() => {
this.$options.methods[method].call(this);
this._cron[method].lastInvocation = + new Date();
}, cron.time),
timerRunning: true,
time: cron.time,
lastInvocation: + new Date()
};
}
};
const mixin = {
mounted(){
if (this.$options.cron !== undefined){
mapOrSingle(this.$options.cron, createTimer.bind(this));
}
this.$cron = {
stop: method => {
let locatedCronMethod = false;
mapOrSingle(this.$options.cron, cron => {
if (cron.method === method){
locatedCronMethod = true;
if(!this._cron[cron.method].timerRunning) return;
clearInterval(this._cron[cron.method].timer);
this._cron[cron.method].timerRunning = false;
}
});
if (!locatedCronMethod){
throw new Error(`Cron method '${method}' does not exist and cannot be stopped.`);
}
},
start: method => {
let locatedCronMethod = false;
mapOrSingle(this.$options.cron, cron => {
if (cron.method === method){
locatedCronMethod = true;
createTimer.call(this, { ...cron, autoStart: true });
}
});
if (!locatedCronMethod){
throw new Error(`Cron method '${method}' does not exist and cannot be started.`);
}
},
restart: method =>{
this.$cron.stop(method);
this.$cron.start(method);
},
time: (method, time) => {
const currentDate = + new Date();
if(!this._cron[method].timerRunning){
this._cron[method].lastInvocation = currentDate;
}
const elapsed = currentDate - this._cron[method].lastInvocation;
this.$cron.stop(method);
if(elapsed > time){
this.$options.methods[method].call(this);
createTimer.call(this, { method, time});
}
else{
setTimeout(() => {
this.$options.methods[method].call(this);
createTimer.call(this, { method, time});
}, time - elapsed);
}
}
};
},
beforeDestroy(){
for(const prop in this._cron){
if(this._cron[prop] !== undefined){
clearInterval(this._cron[prop].timer);
}
}
}
};
const cron = Vue => {
Vue.mixin(mixin);
};
export default cron;
export { mixin as crono };