-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathschedule.js
57 lines (55 loc) · 1.44 KB
/
schedule.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
/** @module liaison/schedule */
define(["./features"], function (has) {
"use strict";
/**
* Calls a function at the end of microtask.
* @function module:liaison/schedule
* @param {Function} callback The function to call at the end of microtask.
*/
return (function () {
/* global setImmediate */
var inFlight,
SCHEDULEID_PREFIX = "_schedule",
seq = 0,
uniqueId = Math.random() + "",
callbacks = {},
pseudoDiv = has("mutation-observer-api") && document.createElement("div");
function runCallbacks() {
for (var anyWorkDone = true; anyWorkDone;) {
anyWorkDone = false;
for (var id in callbacks) {
var callback = callbacks[id];
delete callbacks[id];
callback();
anyWorkDone = true;
}
}
inFlight = false;
}
if (has("mutation-observer-api")) {
pseudoDiv.id = 0;
new MutationObserver(runCallbacks).observe(pseudoDiv, {attributes: true});
} else if (!has("setimmediate-api")) {
window.addEventListener("message", function (event) {
if (event.data === uniqueId) {
runCallbacks();
}
});
}
return function (callback) {
var id = SCHEDULEID_PREFIX + seq++;
callbacks[id] = callback;
if (!inFlight) {
has("mutation-observer-api") ? ++pseudoDiv.id :
has("setimmediate-api") ? setImmediate(runCallbacks) :
window.postMessage(uniqueId, "*");
inFlight = true;
}
return {
remove: function () {
delete callbacks[id];
}
};
};
})();
});