1 | var global = require('../internals/global');
|
2 | var fails = require('../internals/fails');
|
3 | var classof = require('../internals/classof-raw');
|
4 | var bind = require('../internals/bind-context');
|
5 | var html = require('../internals/html');
|
6 | var createElement = require('../internals/document-create-element');
|
7 | var userAgent = require('../internals/user-agent');
|
8 |
|
9 | var location = global.location;
|
10 | var set = global.setImmediate;
|
11 | var clear = global.clearImmediate;
|
12 | var process = global.process;
|
13 | var MessageChannel = global.MessageChannel;
|
14 | var Dispatch = global.Dispatch;
|
15 | var counter = 0;
|
16 | var queue = {};
|
17 | var ONREADYSTATECHANGE = 'onreadystatechange';
|
18 | var defer, channel, port;
|
19 |
|
20 | var run = function (id) {
|
21 |
|
22 | if (queue.hasOwnProperty(id)) {
|
23 | var fn = queue[id];
|
24 | delete queue[id];
|
25 | fn();
|
26 | }
|
27 | };
|
28 |
|
29 | var runner = function (id) {
|
30 | return function () {
|
31 | run(id);
|
32 | };
|
33 | };
|
34 |
|
35 | var listener = function (event) {
|
36 | run(event.data);
|
37 | };
|
38 |
|
39 | var post = function (id) {
|
40 |
|
41 | global.postMessage(id + '', location.protocol + '//' + location.host);
|
42 | };
|
43 |
|
44 |
|
45 | if (!set || !clear) {
|
46 | set = function setImmediate(fn) {
|
47 | var args = [];
|
48 | var i = 1;
|
49 | while (arguments.length > i) args.push(arguments[i++]);
|
50 | queue[++counter] = function () {
|
51 |
|
52 | (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);
|
53 | };
|
54 | defer(counter);
|
55 | return counter;
|
56 | };
|
57 | clear = function clearImmediate(id) {
|
58 | delete queue[id];
|
59 | };
|
60 |
|
61 | if (classof(process) == 'process') {
|
62 | defer = function (id) {
|
63 | process.nextTick(runner(id));
|
64 | };
|
65 |
|
66 | } else if (Dispatch && Dispatch.now) {
|
67 | defer = function (id) {
|
68 | Dispatch.now(runner(id));
|
69 | };
|
70 |
|
71 |
|
72 | } else if (MessageChannel && !/(iphone|ipod|ipad).*applewebkit/i.test(userAgent)) {
|
73 | channel = new MessageChannel();
|
74 | port = channel.port2;
|
75 | channel.port1.onmessage = listener;
|
76 | defer = bind(port.postMessage, port, 1);
|
77 |
|
78 |
|
79 | } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post)) {
|
80 | defer = post;
|
81 | global.addEventListener('message', listener, false);
|
82 |
|
83 | } else if (ONREADYSTATECHANGE in createElement('script')) {
|
84 | defer = function (id) {
|
85 | html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
|
86 | html.removeChild(this);
|
87 | run(id);
|
88 | };
|
89 | };
|
90 |
|
91 | } else {
|
92 | defer = function (id) {
|
93 | setTimeout(runner(id), 0);
|
94 | };
|
95 | }
|
96 | }
|
97 |
|
98 | module.exports = {
|
99 | set: set,
|
100 | clear: clear
|
101 | };
|