\href{https://travis-ci.org/kriskowal/asap}{\texttt{ }}

Promise and asynchronous observer libraries, as well as hand-\/rolled callback programs and libraries, often need a mechanism to postpone the execution of a callback until the next available event. (See \href{http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony}{\texttt{ Designing API’s for Asynchrony}}.) The {\ttfamily asap} function executes a task {\bfseries{as soon as possible}} but not before it returns, waiting only for the completion of the current event and previously scheduled tasks.


\begin{DoxyCode}{0}
\DoxyCodeLine{asap(function () \{}
\DoxyCodeLine{    // ...}
\DoxyCodeLine{\}); }

\end{DoxyCode}


This Common\+JS package provides an {\ttfamily asap} module that exports a function that executes a task function {\itshape as soon as possible}.

ASAP strives to schedule events to occur before yielding for IO, reflow, or redrawing. Each event receives an independent stack, with only platform code in parent frames and the events run in the order they are scheduled.

ASAP provides a fast event queue that will execute tasks until it is empty before yielding to the Java\+Script engine\textquotesingle{}s underlying event-\/loop. When a task gets added to a previously empty event queue, ASAP schedules a flush event, preferring for that event to occur before the Java\+Script engine has an opportunity to perform IO tasks or rendering, thus making the first task and subsequent tasks semantically indistinguishable. ASAP uses a variety of techniques to preserve this invariant on different versions of browsers and Node.\+js.

By design, ASAP prevents input events from being handled until the task queue is empty. If the process is busy enough, this may cause incoming connection requests to be dropped, and may cause existing connections to inform the sender to reduce the transmission rate or stall. ASAP allows this on the theory that, if there is enough work to do, there is no sense in looking for trouble. As a consequence, ASAP can interfere with smooth animation. If your task should be tied to the rendering loop, consider using {\ttfamily request\+Animation\+Frame} instead. A long sequence of tasks can also effect the long running script dialog. If this is a problem, you may be able to use ASAP’s cousin {\ttfamily set\+Immediate} to break long processes into shorter intervals and periodically allow the browser to breathe. {\ttfamily set\+Immediate} will yield for IO, reflow, and repaint events. It also returns a handler and can be canceled. For a {\ttfamily set\+Immediate} shim, consider \href{https://github.com/YuzuJS/setImmediate}{\texttt{ Yuzu\+JS set\+Immediate}}.

Take care. ASAP can sustain infinite recursive calls without warning. It will not halt from a stack overflow, and it will not consume unbounded memory. This is behaviorally equivalent to an infinite loop. Just as with infinite loops, you can monitor a Node.\+js process for this behavior with a heart-\/beat signal. As with infinite loops, a very small amount of caution goes a long way to avoiding problems.


\begin{DoxyCode}{0}
\DoxyCodeLine{function loop() \{}
\DoxyCodeLine{    asap(loop);}
\DoxyCodeLine{\}}
\DoxyCodeLine{loop(); }

\end{DoxyCode}


In browsers, if a task throws an exception, it will not interrupt the flushing of high-\/priority tasks. The exception will be postponed to a later, low-\/priority event to avoid slow-\/downs. In Node.\+js, if a task throws an exception, ASAP will resume flushing only if—and only after—the error is handled by {\ttfamily domain.\+on(\char`\"{}error\char`\"{})} or {\ttfamily process.\+on(\char`\"{}uncaught\+Exception\char`\"{})}.\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3221}{}\doxysection{Raw ASAP}\label{md_sfcode_node_modules_asap_README_autotoc_md3221}
Checking for exceptions comes at a cost. The package also provides an {\ttfamily asap/raw} module that exports the underlying implementation which is faster but stalls if a task throws an exception. This internal version of the ASAP function does not check for errors. If a task does throw an error, it will stall the event queue unless you manually call {\ttfamily raw\+Asap.\+request\+Flush()} before throwing the error, or any time after.

In Node.\+js, {\ttfamily asap/raw} also runs all tasks outside any domain. If you need a task to be bound to your domain, you will have to do it manually.


\begin{DoxyCode}{0}
\DoxyCodeLine{if (process.domain) \{}
\DoxyCodeLine{    task = process.domain.bind(task);}
\DoxyCodeLine{\}}
\DoxyCodeLine{rawAsap(task); }

\end{DoxyCode}
\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3222}{}\doxysection{Tasks}\label{md_sfcode_node_modules_asap_README_autotoc_md3222}
A task may be any object that implements {\ttfamily call()}. A function will suffice, but closures tend not to be reusable and can cause garbage collector churn. Both {\ttfamily asap} and {\ttfamily raw\+Asap} accept task objects to give you the option of recycling task objects or using higher callable object abstractions. See the {\ttfamily asap} source for an illustration.\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3223}{}\doxysection{Compatibility}\label{md_sfcode_node_modules_asap_README_autotoc_md3223}
ASAP is tested on Node.\+js v0.\+10 and in a broad spectrum of web browsers. The following charts capture the browser test results for the most recent release. The first chart shows test results for ASAP running in the main window context. The second chart shows test results for ASAP running in a web worker context. Test results are inconclusive (grey) on browsers that do not support web workers. These data are captured automatically by \mbox{[}Continuous Integration\mbox{]}\mbox{[}\mbox{]}.



\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3224}{}\doxysection{Caveats}\label{md_sfcode_node_modules_asap_README_autotoc_md3224}
When a task is added to an empty event queue, it is not always possible to guarantee that the task queue will begin flushing immediately after the current event. However, once the task queue begins flushing, it will not yield until the queue is empty, even if the queue grows while executing tasks.

The following browsers allow the use of \href{http://dom.spec.whatwg.org/\#mutation-observers}{\texttt{ DOM mutation observers}} to access the HTML \href{http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html\#microtask-queue}{\texttt{ microtask queue}}, and thus begin flushing ASAP\textquotesingle{}s task queue immediately at the end of the current event loop turn, before any rendering or IO\+:


\begin{DoxyItemize}
\item Android 4–4.3
\item Chrome 26–34
\item Firefox 14–29
\item Internet Explorer 11
\item i\+Pad Safari 6–7.1
\item i\+Phone Safari 7–7.1
\item Safari 6–7
\end{DoxyItemize}

In the absense of mutation observers, there are a few browsers, and situations like web workers in some of the above browsers, where \href{http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html\#message-channels}{\texttt{ message channels}} would be a useful way to avoid falling back to timers. Message channels give direct access to the HTML \href{http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html\#concept-task}{\texttt{ task queue}}, so the ASAP task queue would flush after any already queued rendering and IO tasks, but without having the minimum delay imposed by timers. However, among these browsers, Internet Explorer 10 and Safari do not reliably dispatch messages, so they are not worth the trouble to implement.


\begin{DoxyItemize}
\item Internet Explorer 10
\item Safair 5.\+0-\/1
\item Opera 11-\/12
\end{DoxyItemize}

In the absense of mutation observers, these browsers and the following browsers all fall back to using {\ttfamily set\+Timeout} and {\ttfamily set\+Interval} to ensure that a {\ttfamily flush} occurs. The implementation uses both and cancels whatever handler loses the race, since {\ttfamily set\+Timeout} tends to occasionally skip tasks in unisolated circumstances. Timers generally delay the flushing of ASAP\textquotesingle{}s task queue for four milliseconds.


\begin{DoxyItemize}
\item Firefox 3–13
\item Internet Explorer 6–10
\item i\+Pad Safari 4.\+3
\item Lynx 2.\+8.\+7
\end{DoxyItemize}\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3225}{}\doxysection{Heritage}\label{md_sfcode_node_modules_asap_README_autotoc_md3225}
ASAP has been factored out of the \href{https://github.com/kriskowal/q}{\texttt{ Q}} asynchronous promise library. It originally had a naïve implementation in terms of {\ttfamily set\+Timeout}, but \href{http://www.nonblocking.io/2011/06/windownexttick.html}{\texttt{ Malte Ubl}} provided an insight that {\ttfamily post\+Message} might be useful for creating a high-\/priority, no-\/delay event dispatch hack. Since then, Internet Explorer proposed and implemented {\ttfamily set\+Immediate}. Robert Katić began contributing to Q by measuring the performance of the internal implementation of {\ttfamily asap}, paying particular attention to error recovery. Domenic, Robert, and Kris Kowal collectively settled on the current strategy of unrolling the high-\/priority event queue internally regardless of what strategy we used to dispatch the potentially lower-\/priority flush event. Domenic went on to make ASAP cooperate with Node.\+js domains.

For further reading, Nicholas Zakas provided a thorough article on \href{http://www.nczonline.net/blog/2013/07/09/the-case-for-setimmediate/}{\texttt{ The Case for set\+Immediate}}.

Ember’s RSVP promise implementation later \href{https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js}{\texttt{ adopted}} the name ASAP but further developed the implentation. Particularly, The {\ttfamily Message\+Port} implementation was abandoned due to interaction \href{https://github.com/cujojs/when/issues/197}{\texttt{ problems with Mobile Internet Explorer}} in favor of an implementation backed on the newer and more reliable DOM {\ttfamily Mutation\+Observer} interface. These changes were back-\/ported into this library.

In addition, ASAP factored into {\ttfamily asap} and {\ttfamily asap/raw}, such that {\ttfamily asap} remained exception-\/safe, but {\ttfamily asap/raw} provided a tight kernel that could be used for tasks that guaranteed that they would not throw exceptions. This core is useful for promise implementations that capture thrown errors in rejected promises and do not need a second safety net. At the same time, the exception handling in {\ttfamily asap} was factored into separate implementations for Node.\+js and browsers, using the the \mbox{[}Browserify\mbox{]}\mbox{[}Browser Config\mbox{]} {\ttfamily browser} property in {\ttfamily package.\+json} to instruct browser module loaders and bundlers, including \href{https://github.com/substack/node-browserify}{\texttt{ Browserify}}, \href{https://github.com/montagejs/mr}{\texttt{ Mr}}, and \href{https://github.com/montagejs/mop}{\texttt{ Mop}}, to use the browser-\/only implementation.\hypertarget{md_sfcode_node_modules_asap_README_autotoc_md3226}{}\doxysection{License}\label{md_sfcode_node_modules_asap_README_autotoc_md3226}
Copyright 2009-\/2014 by Contributors MIT License (enclosed) 