-
Notifications
You must be signed in to change notification settings - Fork 18
/
setImmediate.js
225 lines (194 loc) · 6.33 KB
/
setImmediate.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/** @license MIT License (c) copyright 2013 original authors */
/**
* setImmediate polyfill / shim
*
* @author Jared Cacurak
* @author Brian Cavalier
* @author John Hann
*
* Based on NobleJS's setImmediate. (https://github.com/NobleJS/setImmediate)
*/
(function (global, define) {
define(function (require) {
"use strict";
var base = require('./lib/_base');
var testCache,
tasks;
testCache = {};
tasks = (function () {
var nextHandle,
tasksByHandle,
currentlyRunningATask;
nextHandle = 1; // Spec says greater than zero
tasksByHandle = {};
currentlyRunningATask = false;
function Task (handler, args) {
this.handler = handler;
this.args = Array.prototype.slice.call(args);
}
Task.prototype.run = function () {
// See steps in section 5 of the spec.
if (base.isFunction(this.handler)) {
// Choice of `thisArg` is not in the setImmediate spec; `undefined` is in the setTimeout spec though:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html
this.handler.apply(undefined, this.args);
}
else {
var scriptSource = '' + this.handler;
eval(scriptSource);
}
};
return {
addFromSetImmediateArguments: function (args) {
var handler,
argsToHandle,
task,
thisHandle;
handler = args[0];
argsToHandle = Array.prototype.slice.call(args, 1);
task = new Task(handler, argsToHandle);
thisHandle = nextHandle++;
tasksByHandle[thisHandle] = task;
return thisHandle;
},
runIfPresent: function (handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (!currentlyRunningATask) {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
task.run();
} finally {
delete tasksByHandle[handle];
currentlyRunningATask = false;
}
}
} else {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
global.setTimeout(function () {
tasks.runIfPresent(handle);
}, 0);
}
},
remove: function (handle) {
delete tasksByHandle[handle];
}
};
}());
function has (name) {
if (base.isFunction(testCache[name])) {
testCache[name] = testCache[name](global);
}
return testCache[name];
}
function add (name, test, now) {
testCache[name] = now ? test(global, d, el) : test;
}
function aliasMicrosoftImplementation (attachTo) {
attachTo.setImmediate = global.msSetImmediate;
attachTo.clearImmediate = global.msClearImmediate;
}
function installPostMessageImplementation (attachTo) {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var MESSAGE_PREFIX = 'cujojs/poly.setImmediate' + Math.random();
function isStringAndStartsWith (string, putativeStart) {
return typeof string === 'string' && string.substring(0, putativeStart.length) === putativeStart;
}
function onGlobalMessage (event) {
// This will catch all incoming messages (even from other windows!), so we need to try reasonably hard to
// avoid letting anyone else trick us into firing off. We test the origin is still this window, and that a
// (randomly generated) unpredictable identifying prefix is present.
if (event.source === global && isStringAndStartsWith(event.data, MESSAGE_PREFIX)) {
var handle = event.data.substring(MESSAGE_PREFIX.length);
tasks.runIfPresent(handle);
}
}
global.addEventListener('message', onGlobalMessage, false);
attachTo.setImmediate = function () {
var handle = tasks.addFromSetImmediateArguments(arguments);
// Make `global` post a message to itself with the handle and identifying prefix, thus asynchronously
// invoking our onGlobalMessage listener above.
global.postMessage(MESSAGE_PREFIX + handle, '*');
return handle;
};
}
function installReadyStateChangeImplementation(attachTo) {
attachTo.setImmediate = function () {
var handle = tasks.addFromSetImmediateArguments(arguments);
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
tasks.runIfPresent(handle);
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
return handle;
};
}
function installSetTimeoutImplementation(attachTo) {
attachTo.setImmediate = function () {
var handle = tasks.addFromSetImmediateArguments(arguments);
global.setTimeout(function () {
tasks.runIfPresent(handle);
}, 0);
return handle;
};
}
add('setimmediate', function (g) {
return base.isFunction(g.setImmediate);
});
add('ms-setimmediate', function (g) {
return base.isFunction(g.msSetImmediate);
});
add('post-message', function (g) {
// Note: this is only for the async postMessage, not the buggy sync
// version in IE8
var postMessageIsAsynchronous,
oldOnMessage;
postMessageIsAsynchronous = true;
oldOnMessage = g.onmessage;
if (!g.postMessage) {
return false;
}
g.onmessage = function () {
postMessageIsAsynchronous = false;
};
g.postMessage('', '*');
g.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
});
add('script-onreadystatechange', function (g) {
return 'document' in g && 'onreadystatechange' in g.document.createElement('script');
});
if (!has('setimmediate')) {
if (has('ms-setimmediate')) {
aliasMicrosoftImplementation(global);
}
else {
if (has('post-message')) {
installPostMessageImplementation(global);
}
else if (has('script-onreadystatechange')) {
installReadyStateChangeImplementation(global);
}
else {
installSetTimeoutImplementation(global);
}
global.clearImmediate = tasks.remove;
}
}
});
}(
this.global || this,
typeof define == 'function' && define.amd
? define
: function (factory) { module.exports = factory(require); }
));