1 | 'use strict';
|
2 | var global = require('../internals/global');
|
3 | var safeGetBuiltIn = require('../internals/safe-get-built-in');
|
4 | var bind = require('../internals/function-bind-context');
|
5 | var macrotask = require('../internals/task').set;
|
6 | var Queue = require('../internals/queue');
|
7 | var IS_IOS = require('../internals/engine-is-ios');
|
8 | var IS_IOS_PEBBLE = require('../internals/engine-is-ios-pebble');
|
9 | var IS_WEBOS_WEBKIT = require('../internals/engine-is-webos-webkit');
|
10 | var IS_NODE = require('../internals/engine-is-node');
|
11 |
|
12 | var MutationObserver = global.MutationObserver || global.WebKitMutationObserver;
|
13 | var document = global.document;
|
14 | var process = global.process;
|
15 | var Promise = global.Promise;
|
16 | var microtask = safeGetBuiltIn('queueMicrotask');
|
17 | var notify, toggle, node, promise, then;
|
18 |
|
19 |
|
20 | if (!microtask) {
|
21 | var queue = new Queue();
|
22 |
|
23 | var flush = function () {
|
24 | var parent, fn;
|
25 | if (IS_NODE && (parent = process.domain)) parent.exit();
|
26 | while (fn = queue.get()) try {
|
27 | fn();
|
28 | } catch (error) {
|
29 | if (queue.head) notify();
|
30 | throw error;
|
31 | }
|
32 | if (parent) parent.enter();
|
33 | };
|
34 |
|
35 |
|
36 |
|
37 | if (!IS_IOS && !IS_NODE && !IS_WEBOS_WEBKIT && MutationObserver && document) {
|
38 | toggle = true;
|
39 | node = document.createTextNode('');
|
40 | new MutationObserver(flush).observe(node, { characterData: true });
|
41 | notify = function () {
|
42 | node.data = toggle = !toggle;
|
43 | };
|
44 |
|
45 | } else if (!IS_IOS_PEBBLE && Promise && Promise.resolve) {
|
46 |
|
47 | promise = Promise.resolve(undefined);
|
48 |
|
49 | promise.constructor = Promise;
|
50 | then = bind(promise.then, promise);
|
51 | notify = function () {
|
52 | then(flush);
|
53 | };
|
54 |
|
55 | } else if (IS_NODE) {
|
56 | notify = function () {
|
57 | process.nextTick(flush);
|
58 | };
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | } else {
|
66 |
|
67 | macrotask = bind(macrotask, global);
|
68 | notify = function () {
|
69 | macrotask(flush);
|
70 | };
|
71 | }
|
72 |
|
73 | microtask = function (fn) {
|
74 | if (!queue.head) notify();
|
75 | queue.add(fn);
|
76 | };
|
77 | }
|
78 |
|
79 | module.exports = microtask;
|