forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task-loop.js
73 lines (64 loc) · 1.51 KB
/
task-loop.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
import EventHandler from './event-handler';
export default class TaskLoop extends EventHandler {
constructor (hls, ...events) {
super(hls, ...events);
this._tickInterval = null;
this._tickCallCount = 0;
}
/**
* @override
*/
destroy () {
this.clearInterval();
super.destroy();
}
/**
* @returns {boolean}
*/
hasInterval () {
return this._tickInterval !== null;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
setInterval (millis) {
if (!this._tickInterval) {
this._tickInterval = setInterval(this.tick.bind(this, false), millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
clearInterval () {
if (this._tickInterval) {
clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
*
* @param {Wether to force async} forceAsync
* @returns {boolean} True when async, false when sync
*/
tick () {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick();
if (this._tickCallCount > 1)
setTimeout(this.tick.bind(this), 0);
this._tickCallCount = 0;
}
}
/**
* For subclass to implement task logic
* @abstract
*/
doTick () {
throw new Error('TaskLoop is abstract and `doLoop` must be implemented');
}
}