This repository has been archived by the owner on Aug 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
setimmediate.js
61 lines (55 loc) · 1.54 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
/**
* setImmediate polyfill v1.0.1, supports IE9+
* © 2014–2015 Dmitry Korobkin
* Released under the MIT license
* github.com/Octane/setImmediate
*/
window.setImmediate || function () {'use strict';
var uid = 0;
var storage = {};
var firstCall = true;
var slice = Array.prototype.slice;
var message = 'setImmediatePolyfillMessage';
function fastApply(args) {
var func = args[0];
switch (args.length) {
case 1:
return func();
case 2:
return func(args[1]);
case 3:
return func(args[1], args[2]);
}
return func.apply(window, slice.call(args, 1));
}
function callback(event) {
var key = event.data;
var data;
if (typeof key == 'string' && key.indexOf(message) == 0) {
data = storage[key];
if (data) {
delete storage[key];
fastApply(data);
}
}
}
window.setImmediate = function setImmediate() {
var id = uid++;
var key = message + id;
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments[i];
}
storage[key] = args;
if (firstCall) {
firstCall = false;
window.addEventListener('message', callback);
}
window.postMessage(key, '*');
return id;
};
window.clearImmediate = function clearImmediate(id) {
delete storage[message + id];
};
}();