forked from iNavFlight/inav-configurator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeouts.js
66 lines (50 loc) · 1.69 KB
/
timeouts.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
'use strict';
var timeout = (function () {
var privateScope = {},
publicScope = {};
privateScope.timeouts = [];
/**
*
* @param {string} name
* @param {function } code
* @param {number} timeout
* @returns {{name: *, timer: null, timeout: *}}
*/
publicScope.add = function (name, code, timeout) {
var data = {'name': name, 'timer': null, 'timeout': timeout};
// start timer with "cleaning" callback
data.timer = setTimeout(function() {
code(); // execute code
// remove object from array
var index = privateScope.timeouts.indexOf(data);
if (index > -1) privateScope.timeouts.splice(index, 1);
}, timeout);
privateScope.timeouts.push(data); // push to primary timeout array
return data;
};
publicScope.remove = function (name) {
for (var i = 0; i < privateScope.timeouts.length; i++) {
if (privateScope.timeouts[i].name == name) {
clearTimeout(privateScope.timeouts[i].timer); // stop timer
privateScope.timeouts.splice(i, 1); // remove element/object from array
return true;
}
}
return false;
};
/**
*
* @returns {number} number of killed timeouts
*/
publicScope.killAll = function () {
var timers_killed = 0;
for (var i = 0; i < privateScope.timeouts.length; i++) {
clearTimeout(privateScope.timeouts[i].timer); // stop timer
timers_killed++;
}
privateScope.timeouts = []; // drop objects
return timers_killed;
};
return publicScope;
})();
module.exports = timeout;