lib/goog/async/nexttick.js

1// Copyright 2013 The Closure Library Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS-IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/**
16 * @fileoverview Provides a function to schedule running a function as soon
17 * as possible after the current JS execution stops and yields to the event
18 * loop.
19 *
20 */
21
22goog.provide('goog.async.nextTick');
23goog.provide('goog.async.throwException');
24
25goog.require('goog.debug.entryPointRegistry');
26goog.require('goog.functions');
27goog.require('goog.labs.userAgent.browser');
28
29
30/**
31 * Throw an item without interrupting the current execution context. For
32 * example, if processing a group of items in a loop, sometimes it is useful
33 * to report an error while still allowing the rest of the batch to be
34 * processed.
35 * @param {*} exception
36 */
37goog.async.throwException = function(exception) {
38 // Each throw needs to be in its own context.
39 goog.global.setTimeout(function() { throw exception; }, 0);
40};
41
42
43/**
44 * Fires the provided callbacks as soon as possible after the current JS
45 * execution context. setTimeout(…, 0) takes at least 4ms when called from
46 * within another setTimeout(…, 0) for legacy reasons.
47 *
48 * This will not schedule the callback as a microtask (i.e. a task that can
49 * preempt user input or networking callbacks). It is meant to emulate what
50 * setTimeout(_, 0) would do if it were not throttled. If you desire microtask
51 * behavior, use {@see goog.Promise} instead.
52 *
53 * @param {function(this:SCOPE)} callback Callback function to fire as soon as
54 * possible.
55 * @param {SCOPE=} opt_context Object in whose scope to call the listener.
56 * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that
57 * ensures correctness at the cost of speed. See comments for details.
58 * @template SCOPE
59 */
60goog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) {
61 var cb = callback;
62 if (opt_context) {
63 cb = goog.bind(callback, opt_context);
64 }
65 cb = goog.async.nextTick.wrapCallback_(cb);
66 // window.setImmediate was introduced and currently only supported by IE10+,
67 // but due to a bug in the implementation it is not guaranteed that
68 // setImmediate is faster than setTimeout nor that setImmediate N is before
69 // setImmediate N+1. That is why we do not use the native version if
70 // available. We do, however, call setImmediate if it is a normal function
71 // because that indicates that it has been replaced by goog.testing.MockClock
72 // which we do want to support.
73 // See
74 // http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10
75 //
76 // Note we do allow callers to also request setImmediate if they are willing
77 // to accept the possible tradeoffs of incorrectness in exchange for speed.
78 // The IE fallback of readystate change is much slower.
79 if (goog.isFunction(goog.global.setImmediate) &&
80 (opt_useSetImmediate || !goog.global.Window ||
81 goog.global.Window.prototype.setImmediate != goog.global.setImmediate)) {
82 goog.global.setImmediate(cb);
83 return;
84 }
85
86 // Look for and cache the custom fallback version of setImmediate.
87 if (!goog.async.nextTick.setImmediate_) {
88 goog.async.nextTick.setImmediate_ =
89 goog.async.nextTick.getSetImmediateEmulator_();
90 }
91 goog.async.nextTick.setImmediate_(cb);
92};
93
94
95/**
96 * Cache for the setImmediate implementation.
97 * @type {function(function())}
98 * @private
99 */
100goog.async.nextTick.setImmediate_;
101
102
103/**
104 * Determines the best possible implementation to run a function as soon as
105 * the JS event loop is idle.
106 * @return {function(function())} The "setImmediate" implementation.
107 * @private
108 */
109goog.async.nextTick.getSetImmediateEmulator_ = function() {
110 // Create a private message channel and use it to postMessage empty messages
111 // to ourselves.
112 var Channel = goog.global['MessageChannel'];
113 // If MessageChannel is not available and we are in a browser, implement
114 // an iframe based polyfill in browsers that have postMessage and
115 // document.addEventListener. The latter excludes IE8 because it has a
116 // synchronous postMessage implementation.
117 if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&
118 window.postMessage && window.addEventListener) {
119 /** @constructor */
120 Channel = function() {
121 // Make an empty, invisible iframe.
122 var iframe = document.createElement('iframe');
123 iframe.style.display = 'none';
124 iframe.src = '';
125 document.documentElement.appendChild(iframe);
126 var win = iframe.contentWindow;
127 var doc = win.document;
128 doc.open();
129 doc.write('');
130 doc.close();
131 // Do not post anything sensitive over this channel, as the workaround for
132 // pages with file: origin could allow that information to be modified or
133 // intercepted.
134 var message = 'callImmediate' + Math.random();
135 // The same origin policy rejects attempts to postMessage from file: urls
136 // unless the origin is '*'.
137 // TODO(b/16335441): Use '*' origin for data: and other similar protocols.
138 var origin = win.location.protocol == 'file:' ?
139 '*' : win.location.protocol + '//' + win.location.host;
140 var onmessage = goog.bind(function(e) {
141 // Validate origin and message to make sure that this message was
142 // intended for us. If the origin is set to '*' (see above) only the
143 // message needs to match since, for example, '*' != 'file://'. Allowing
144 // the wildcard is ok, as we are not concerned with security here.
145 if ((origin != '*' && e.origin != origin) || e.data != message) {
146 return;
147 }
148 this['port1'].onmessage();
149 }, this);
150 win.addEventListener('message', onmessage, false);
151 this['port1'] = {};
152 this['port2'] = {
153 postMessage: function() {
154 win.postMessage(message, origin);
155 }
156 };
157 };
158 }
159 if (typeof Channel !== 'undefined' &&
160 (!goog.labs.userAgent.browser.isIE())) {
161 // Exclude all of IE due to
162 // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/
163 // which allows starving postMessage with a busy setTimeout loop.
164 // This currently affects IE10 and IE11 which would otherwise be able
165 // to use the postMessage based fallbacks.
166 var channel = new Channel();
167 // Use a fifo linked list to call callbacks in the right order.
168 var head = {};
169 var tail = head;
170 channel['port1'].onmessage = function() {
171 if (goog.isDef(head.next)) {
172 head = head.next;
173 var cb = head.cb;
174 head.cb = null;
175 cb();
176 }
177 };
178 return function(cb) {
179 tail.next = {
180 cb: cb
181 };
182 tail = tail.next;
183 channel['port2'].postMessage(0);
184 };
185 }
186 // Implementation for IE6+: Script elements fire an asynchronous
187 // onreadystatechange event when inserted into the DOM.
188 if (typeof document !== 'undefined' && 'onreadystatechange' in
189 document.createElement('script')) {
190 return function(cb) {
191 var script = document.createElement('script');
192 script.onreadystatechange = function() {
193 // Clean up and call the callback.
194 script.onreadystatechange = null;
195 script.parentNode.removeChild(script);
196 script = null;
197 cb();
198 cb = null;
199 };
200 document.documentElement.appendChild(script);
201 };
202 }
203 // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms
204 // or more.
205 return function(cb) {
206 goog.global.setTimeout(cb, 0);
207 };
208};
209
210
211/**
212 * Helper function that is overrided to protect callbacks with entry point
213 * monitor if the application monitors entry points.
214 * @param {function()} callback Callback function to fire as soon as possible.
215 * @return {function()} The wrapped callback.
216 * @private
217 */
218goog.async.nextTick.wrapCallback_ = goog.functions.identity;
219
220
221// Register the callback function as an entry point, so that it can be
222// monitored for exception handling, etc. This has to be done in this file
223// since it requires special code to handle all browsers.
224goog.debug.entryPointRegistry.register(
225 /**
226 * @param {function(!Function): !Function} transformer The transforming
227 * function.
228 */
229 function(transformer) {
230 goog.async.nextTick.wrapCallback_ = transformer;
231 });