Search completed in 1.98 seconds.
628 results for "async":
Your results are loading. Please wait...
Making asynchronous programming easier with async and await - Learn web development
previous overview: asynchronous next more recent additions to the javascript language are async functions and the await keyword, part of the so-called ecmascript 2017 javascript edition (see ecmascript next support in mozilla).
... these features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards.
... they make async code look more like old-school synchronous code, so they're well worth learning.
...And 46 more matches
async function - JavaScript
an async function is a function declared with the async keyword.
... async functions are instances of the asyncfunction constructor, and the await keyword is permitted within them.
... the async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
...And 27 more matches
Introducing asynchronous JavaScript - Learn web development
previous overview: asynchronous next in this article we briefly recap the problems associated with synchronous javascript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can help us solve such problems.
... objective: to gain familiarity with what asynchronous javascript is, how it differs from synchronous javascript, and what use cases it has.
... synchronous javascript to allow us to understand what asynchronous javascript is, we ought to start off by making sure we understand what synchronous javascript is.
...And 25 more matches
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird.
... boilerplate add the following code to the top of your test file to import everything you need: load("../../mailnews/resources/loghelper.js"); load("../../mailnews/resources/asynctestutils.js"); load("../../mailnews/resources/messagegenerator.js"); load("../../mailnews/resources/messagemodifier.js"); load("../../mailnews/resources/messageinjection.js"); if the directory where you are adding the tests does not have a head_*.js file that has the two following lines, add them at the top of your test file (before the lines shown above): load("../../mailnews/resources/maildirservice.js"); load("../../mailnews/resources/mailtestutils.js"); at the bottom of the test file, add the following: var tests =[ //...
... list your tests here ]; function run_test() { configure_message_injection({mode: "local"}); async_run_tests(tests); } asynchronous testing basics why do we need it?
...And 15 more matches
Graceful asynchronous programming with Promises - Learn web development
previous overview: asynchronous next promises are a comparatively new feature of the javascript language that allow you to defer further actions until after a previous action has completed, or respond to its failure.
... this is useful for setting up a sequence of async operations to work correctly.
... generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is.
...And 14 more matches
General asynchronous programming concepts - Learn web development
overview: asynchronous next in this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript.
... objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript.
... asynchronous?
...And 12 more matches
AsyncFunction - JavaScript
the asyncfunction constructor creates a new async function object.
... in javascript, every asynchronous function is actually an asyncfunction object.
... note that asyncfunction is not a global object.
...And 8 more matches
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
the debug.mstraceasynccallbackcompleted function indicates that an asynchronous operation has completed.
... syntax debug.mstraceasynccallbackcompleted() parameters asyncoperationid the id associated with the asynchronous operation.
... status optional the status of the asynchronous operation.
...And 7 more matches
Asynchronous JavaScript - Learn web development
in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
... get started prerequisites asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this.
... if you are not familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module.
...And 7 more matches
Synchronous and asynchronous requests - Web APIs
xmlhttprequest supports both synchronous and asynchronous communications.
... in general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.
... asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received.
...And 7 more matches
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
the term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete).
... in computing, the word "asynchronous" is used in two major contexts.
... networking and communications asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt.
...And 6 more matches
nsIAsyncInputStream
xpcom/io/nsiasyncinputstream.idlscriptable please add a summary to this article.
...if the stream implements nsiasyncinputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait() method).
...nor is it necessary that a non-blocking nsiinputstream implementation also implement nsiasyncinputstream.
...And 6 more matches
nsIAsyncOutputStream
xpcom/io/nsiasyncoutputstream.idlscriptable please add a summary to this article.
...if the stream implements nsiasyncoutputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait() method).
...nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream.
...And 6 more matches
Symbol.asyncIterator - JavaScript
the symbol.asynciterator well-known symbol specifies the default asynciterator for an object.
... if this property is set on an object, it is an async iterable and can be used in a for await...of loop.
... description the symbol.asynciterator symbol is a builtin symbol that is used to access an object's @@asynciterator method.
...And 6 more matches
async function expression - JavaScript
the async function keyword can be used to define async functions inside expressions.
... you can also define async functions using an async function statement.
... syntax async function [name]([param1[, param2[, ..., paramn]]]) { statements } as of es2015, you can also use arrow functions.
...And 6 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
previous overview: asynchronous next this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g.
... objective: to understand asynchronous loops and intervals and what they are useful for.
... introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop.
...And 5 more matches
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
the debug.mstraceasynccallbackstarting function associates the callback stack with a previously specified asynchronous operation.
... syntax debug.mstraceasynccallbackstarting(asyncoperationid) parameters asyncoperationid the id associated with the asynchronous operation.
... remarks call this function in the callback function for the asynchronous operation after the call to debug.mstraceasyncoperationcompleted.
...And 4 more matches
Async scripts for asm.js - Game development
every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process.
... in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28).
... putting async into action getting async compilation is easy: when writing your javascript, just use the async attribute like so: <script async src="file.js"></script> or, to do the same thing via script: var script = document.createelement('script'); script.src = "file.js"; document.body.appendchild(script); (scripts created from script default to async.) the default html shell emscripten generates produces the latter.
...And 3 more matches
Debug.msUpdateAsyncCallbackRelation - Archive of obsolete content
the debug.msupdateasynccallbackrelation function updates the relationship status between a synchronous work item and the associated asynchronous operation.
... syntax debug.msupdateasynccallbackrelation(relatedasyncoperationid, relationtype) parameters relatedasyncoperationid the id associated with the asynchronous operation.
... remarks the synchronous work item is typically the callback function for the asynchronous operation.
...And 2 more matches
AsyncShutdown.jsm
managing safe shutdown of asynchronous services.
... asyncshutdown.profilebeforechange.addblocker( "add-on manager: shutting down", function condition() { let promise = ...
...if you need a new phase added to asyncshutdown, please file a bug.
...And 2 more matches
NPN_PluginThreadAsyncCall - Archive of obsolete content
syntax #include <npapi.h> void npn_pluginthreadasynccall(npp plugin, void (*func)(void *), void *userdata); parameters the function has the following parameters: plugin pointer to the current plug-in instance.
... description causes asynchronous execution of the specified function pointer on the "plug-in thread", passing in the specified user data pointer when it is called.
...it is the application's responsibility to perform any synchronization between the thread calling npn_pluginthreadasynccall() and the thread on which the call is eventually executed.
...calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately.
mozIStorageAsyncStatement
an asynchronous sql statement.
... this differs from mozistoragestatement by only being usable for asynchronous execution.
... (mozistoragestatement can be used for both synchronous and asynchronous purposes.) this specialization for asynchronous operation allows us to avoid needing to acquire synchronization primitives also used by the asynchronous execution thread.
... in contrast, mozistoragestatement may need to acquire the primitives and consequently can cause the main thread to lock for extended intervals while the asynchronous thread performs some long-running operation.
SourceBuffer.appendBufferAsync() - Web APIs
the appendbufferasync() method of the sourcebuffer interface begins the process of asynchronously appending media segment data from an arraybuffer or arraybufferview object to the sourcebuffer.
... syntax appendpromise = sourcebuffer.appendbufferasync(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer.
... example this simplified example async function, fillsourcebuffer(), takes as input parameters buffersource, buffer, and a sourcebuffer to which to append the source media from the buffer.
... async function fillsourcebuffer(buffer, msbuffer) { try { while(true) { await msbuffer.appendbufferasync(buffer); } } catch(e) { handleexception(e); } } specifications not currently part of any specification.
SourceBuffer.removeAsync() - Web APIs
the removeasync() method of the sourcebuffer interface starts the process of asynchronously removing from the sourcebuffer media segments found within a specific time range.
... syntax removepromise = sourcebuffer.removeasync(start, end); parameters start a double representing the start of the time range, in seconds.
... example this example establishes an asynchronous function, emptysourcebuffer(), which simply clears the contents of the specified sourcebuffer.
... async function emptysourcebuffer(msbuffer) { await msbuffer.removeasync(0, infinity).catch(function(e) { handleexception(e); } } specifications not currently part of the mse specification.
mozbrowserasyncscroll
the mozbrowserasyncscroll event is fired when the content of a browser <iframe> is scrolled.
... note: for performance reasons, this event is asynchronous.
... examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserasyncscroll", function( event ) { console.log("the scroll top position of the document is:" + event.details.top + "px"); }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozIAsyncHistory
toolkit/components/places/moziasynchistory.idlscriptable this interface allows you to add multiple visits to a single url in a batch.
... 1.0 66 introduced gecko 24.0 inherits from: nsisupports last changed in gecko 24.0 (firefox 24.0 / thunderbird 24.0 / seamonkey 2.21) implemented by: @mozilla.org/browser/history;1 as a service: var asynchistory = components.classes["@mozilla.org/browser/history;1"] .getservice(components.interfaces.moziasynchistory); method overview void getplacesinfo(in jsval aplaceidentifiers, in mozivisitinfocallback acallback); void isurivisited(in nsiuri auri, in mozivisitedstatuscallback acallback); void updateplaces(in moziplaceinfo, [optional] in mozivisitinfocallback acallback); methods getplacesinfo() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to r...
... isurivisited() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request.
nsIAsyncStreamCopier
netwerk/base/public/nsiasyncstreamcopier.idlscriptable this interface is used to copy the contents of one stream to another.
... inherits from: nsirequest last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void asynccopy(in nsirequestobserver aobserver, in nsisupports aobservercontext); void init(in nsiinputstream asource, in nsioutputstream asink, in nsieventtarget atarget, in boolean asourcebuffered, in boolean asinkbuffered, in unsigned long achunksize, in boolean aclosesource, in boolean aclosesink); methods asynccopy() starts the copy operation.
...void asynccopy( in nsirequestobserver aobserver, in nsisupports aobservercontext ); parameters aobserver receives notifications.
nsIAsyncVerifyRedirectCallback
netwerk/base/public/nsiasyncverifyredirectcallback.idlscriptable implement this interface to receive a callback that lets you know whether an asynchronous redirect was verified or vetoed.
... 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface implements the callbacks passed to the nsichanneleventsink.asynconchannelredirect() method.
... method overview void onredirectverifycallback(in nsresult result); methods onredirectverifycallback() implements the asynchronous callback passed to nsichanneleventsink.asynconchannelredirect().
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
document.async can be set to indicate whether a xmldocument.load() call should be an asynchronous or synchronous request.
... true is the default value, indicating that documents should be loaded asynchronously.
... (it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
mozIAsyncFavicons
toolkit/components/places/moziasyncfavicons.idlscriptable interface for accessing the favicon service asynchronously.
... setandfetchfaviconforpage() declares that a given page uses a favicon with the given uri and attempts to fetch and save the icon data by loading the favicon uri through a asynchronous network request.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
indicates that the callback stack associated with a previously specified asynchronous operation has completed.
Debug.msTraceAsyncOperationStarting - Archive of obsolete content
initiates a trace for an asynchronous operation.
Index - Web APIs
WebAPIIndex
73 animation.pending api, animation, animations, property, reference, web animations, web animations api the read-only animation.pending property of the web animations api indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
... 273 beacon api guide, overview, web performance, user behavior tracker, user tracker the beacon interface is used to schedule an asynchronous and non-blocking request to a web server.
... 274 using the beacon api guide, web performance the beacon interface schedules an asynchronous and non-blocking request to a web server.
...And 43 more matches
Bytecode Descriptions
toasynciter stack: iter, next ⇒ asynciter create and push an async iterator wrapping the sync iterator iter.
...implements: createasynctosynciterator.
... generators and async functions generator stack: ⇒ gen create and push a generator object for the current frame.
...And 31 more matches
Index
MozillaTechXPCOMIndex
193 moziasyncfavicons interfaces, interfaces:scriptable, places nsifaviconservice handles this interface, so you do not need to directly create a new service.
... 194 moziasynchistory interfaces, interfaces:scriptable, places, xpcom interface reference implemented by: @mozilla.org/browser/history;1 as a service: 195 mozicoloranalyzer interfaces, interfaces:scriptable, places, reference, xpcom api reference, xpcom interface reference given an image uri, find the most representative color for that image based on the frequency of each color.
... 204 mozistorageasyncstatement stub an asynchronous sql statement.
...And 28 more matches
mozIStorageConnection
method overview void asyncclose([optional] in mozistoragecompletioncallback acallback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); void close(); void committransaction(); void createaggregatefunction(in autf8string afunctionname, in long anumarguments, in mozistorageaggreg...
...atefunction afunction); mozistorageasyncstatement createasyncstatement(in autf8string asqlstatement); void createfunction(in autf8string afunctionname, in long anumarguments, in mozistoragefunction afunction); mozistoragestatement createstatement(in autf8string asqlstatement); void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, [optional] in mozistoragestatementcallback acallback ); void executesimplesql(in autf8string asqlstatement); boolean indexexists(in autf8string aindexname); void preload(); obsolete since gecko 1.9 void removefunction(in autf8strin...
... note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads.
...And 17 more matches
IPDL Tutorial
the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol.
... because protocol messages are represented as c++ methods, it's easy to forget that they are in fact asynchronous messages: by default the c++ method will return immediately, before the message has been delivered.
... // pdirection.ipdl async protocol pdirection { child: async foo(); // can be sent from-parent-to-child parent: async bar(); // can be sent from-child-to-parent both: async baz(); // can be sent both ways }; // pdirectionparent.h class pdirectionparent { protected: virtual void recvbar() = 0; virtual void recvbaz() = 0; public: void sendfoo() { /* boilerplate */ } void sendbaz() { /* boilerplate */ } }...
...And 16 more matches
Choosing the right approach - Learn web development
previous overview: asynchronous to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate.
... objective: to be able to make a sound choice of when to use different asynchronous programming techniques.
... asynchronous callbacks generally found in old-style apis, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback can in turn do something with the result.
...And 15 more matches
core/promise - Archive of obsolete content
implementation of promises to make asynchronous programming easier.
... rationale most of the js apis are asynchronous complementing its non-blocking nature.
... flat chaining you can use then for chaining intermediate operations on promises (var data = readasync().then(parse).then(extract)).
...And 14 more matches
Using Promises - JavaScript
« previousnext » a promise is an object representing the eventual completion or failure of an asynchronous operation.
... imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs.
... here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call.
...And 12 more matches
for await...of - JavaScript
the for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined async/sync iterables.
...like the await operator, the statement can only be used inside an async function.
... for await...of doesn't work with async iterators that are not async iterables.
...And 12 more matches
Debug - Archive of obsolete content
constants async callback status codes contant description value debug.ms_async_callback_status_assign_delegate the synchronous work item assigned a callback or continuation to be run by an asynchronous operation.
... 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operation.
... 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation.
...And 10 more matches
AddonManager
the majority of the methods are asynchronous meaning that results are delivered through callbacks passed to the method.
... callbacks installcallback() a callback that is passed a single addoninstall void installcallback( in addoninstall install ) parameters install the addoninstall passed back from the asynchronous request installlistcallback() a callback that is passed an array of addoninstalls void installlistcallback( in addoninstall installs[] ) parameters installs the array of addoninstalls passed back from the asynchronous request addoncallback() a callback that is passed a single addon void addoncallback( in addon addon ) parameters addon the addon passed back from the as...
... addonlistcallback() a callback that is passed an array of addons void addonlistcallback( in addon addons[] ) parameters addons the array of addons passed back from the asynchronous request constants addoninstall states constant description state_available an install that is waiting to be started.
...And 10 more matches
Storage
if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose() method.
... binding multiple sets of parameters starting in gecko 1.9.2 (firefox 3.6), there's a new, more convenient way to bind multiple sets of parameters at once prior to executing your statement asynchronously.
... this api is only available for asynchronous execution.
...And 10 more matches
Promise - JavaScript
the promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
...it allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
... this lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
...And 10 more matches
Index - Archive of obsolete content
80 core/promise implementation of promises to make asynchronous programming easier.
... 304 promises add-ons, examples, snippets, async no summary!
... 2005 array.observe() array, javascript, method, obsolete the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
...And 8 more matches
Necko walkthrough
has onstartrequest, onstoprequest, ondataavailable, the three functions in which channel responses are received asynchronously.
... nshttpchannel::asyncopen called from openuri; openchannel isn't named the best, since the opening happens in the context of openuri, its calling function.
...but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response callback...) channel->asyncopen.
...And 8 more matches
Optimizing startup performance - Web Performance
instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible.
... why is it important to be asynchronous?
... if you're starting your project from scratch, it's usually pretty easy to just write everything the "right way," making appropriate bits of the code asynchronous.
...And 8 more matches
nsIFaviconService
note: this is an asynchronous operation; when it completes, a "places-favicons-expired" notification is dispatched through the observer's service.
...you should use the new async api moziasyncfavicons.getfavicondataforpage() instead.
...you should use the new async api moziasyncfavicons.getfavicondataforpage() instead.
...And 7 more matches
nsIProtocolProxyService
to access the service use: var pps = components.classes["@mozilla.org/network/protocol-proxy-service;1"] .getservice(components.interfaces.nsiprotocolproxyservice); method overview deprecated since gecko 18 nsiproxyinfo resolve(in nsiuri auri, in unsigned long aflags); nsicancelable asyncresolve(in nsiuri auri, in unsigned long aflags,in nsiprotocolproxycallback acallback); nsiproxyinfo newproxyinfo(in acstring atype, in autf8string ahost,in long aport, in unsigned long aflags, in unsigned long afailovertimeout, in nsiproxyinfo afailoverproxy); nsiproxyinfo getfailoverforproxy(in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason); void registe...
... by passing this flag to resolve, one can failover to asyncresolve to avoid locking up the calling thread if a pac query is required.
...use resolveasync instead previous doc this method returns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri.
...And 7 more matches
Introduction to the File and Directory Entries API - Web APIs
overview the file and directory entries api includes both asynchronous and synchronous versions of the interfaces.
... the asynchronous api can be used in cases where you don't want an outstanding operation to block the ui.
... big concepts before you start using the file and directory entries api, you need to understand a few concepts: the file and directory entries api is a virtual representation of a file system the file and directory entries api can use different storage types browsers impose storage quota the file and directory entries api has asynchronous and synchronous versions when using the asynchronous api, always use the error callbacks the file and directory entries api interacts with other apis the file and directory entries api is case-sensitive the file and directory entries api is a virtual representation of a file system the api doesn't give you access to the local file system, nor is the sandbox really a section of the fi...
...And 7 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
async function start() { try { const stream = await navigator.mediadevices.getusermedia(constraints); for (const track of stream.gettracks()) { pc.addtrack(track, stream); } selfvideo.srcobject = stream; } catch(err) { console.error(err); } } this isn't appreciably different from older webrtc connection establishment code.
... let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer = true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.error(err); } finally { makingoffer = false; } }; note that setlocaldescription() without arguments automatically creates and sets the appropriate description based on the current signalingstate.
...to avoid races, we'll use this value later instead of the signaling state to determine whether or not an offer is being processed because the value of signalingstate changes asynchronously, introducing a glare opportunity.
...And 7 more matches
Index - Learn web development
49 asynchronous javascript beginner, codingscripting, guide, javascript, landing, promises, async, asynchronous, await, callbacks, requestanimationframe, setinterval, settimeout in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
... 50 choosing the right approach beginner, intervals, javascript, learn, optimize, promises, async, asynchronous, await, requestanimationframe, setinterval, settimeout, timeouts to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate.
... 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, codingscripting, guide, intervals, javascript, loops, asynchronous, requestanimationframe, setinterval, settimeout, timeouts this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g.
...And 6 more matches
nsIChannel
then, the uri can be fetched by calling open() or asyncopen().
... method overview void asyncopen(in nsistreamlistener alistener, in nsisupports acontext); nsiinputstream open(); attributes attribute type description contentcharset acstring the character set of the channel's content if available and if applicable.
... setting contenttype between the time that asyncopen() is called and the time when onstartrequest is fired has undefined behavior at this time.
...And 6 more matches
DevTools API - Firefox Developer Tools
{toolid}-build(panel) the frame for a tool has loaded and the toolpanel.build() method has been called but the asynchronous initialization has not started.
... {toolid}-ready(panel) the asynchronous initialization for a tool has completed and it is ready to be used.
...a method that can be used to perform asynchronous initialization.
...And 6 more matches
PaymentRequest.show() - Web APIs
processing the result and, if necessary, calling paymentresponse.retry() to retry a failed payment can all be done either asynchronously or synchronously, depending on your needs.
... for the best user experience, asynchronous solutions are typically the best way to go.
... most examples on mdn and elsewhere use async/await to wait asynchronously while results are validated and so forth.
...And 6 more matches
test/utils - Archive of obsolete content
, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous.
... to make them asynchronous, pass a third argument done, which is a function to call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert, done) { removeallbookmarksasync(function () { done(); }); }); require('sdk/test').run(exports); globals functions before(exports, beforefn) runs beforefn before each test in the file.
... may be asynchronous if beforefn accepts a third argument, which is a callback.
...And 5 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywindow = window.open("about:blank"); mywindow.location.href = "http://www.ibm.com"; } </script> the problem with the code is that window.open is asynchronous -- it does not block the javascript execution until the window has finished loading.
... mydocument = new activexobject("microsoft.xmldom"); mydocument.async = false; mydocument.loadxml(xmlstring); } else { // not supported.
... after instantiating the object using new xmlhttprequest(), you can use the open method to specify what type of request (get or post) you use, which file you load, and if it is asynchronous or not.
...And 5 more matches
Communicating with frame scripts
the api is mostly symmetrical, with one major exception: frame scripts can send asynchronous or synchronous messages to chrome, but chrome can only send asynchronous messages to content.
... content to chrome the frame script can choose to send synchronous or asynchronous messages to chrome code.
... asynchronous messaging to send an asynchronous message the frame script uses the global sendasyncmessage() function: // frame script sendasyncmessage("my-addon@me.org:my-e10s-extension-message"); sendasyncmessage() takes one mandatory parameter, which is the name of the message.
...And 5 more matches
HTTP Cache
unimplemented or underimplemented functionality: asyncevictstorage (bug 977766), asyncvisitstorage (bug 916052) nsicacheentryopencallback //github.com/realityripple/uxp/blob/master/netwerk/cache2/nsicacheentryopencallback.idl the result of nsicachestorage.asyncopenuri is always and only sent to callbacks on this interface.
... these callbacks are ensured to be invoked when asyncopenuri returns ns_ok.
... important difference in behavior from the old cache: when the cache entry object is already present in memory or open as “force-new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e.
...And 5 more matches
Extending a Protocol
include protocol pwindowglobal; namespace mozilla { namespace dom { async refcounted protocol pecho { manager pwindowglobal; parent: async echo(nscstring data) returns (nscstring aresult); async __delete__(); }; } // namespace dom } // namespace mozilla now, edit "./dom/ipc/moz.build" file and add 'pecho.ipdl', to the ipdl_sources array.
... async refcounted protocol pecho {....} - this protocol is "async", meaning we are going to use mozpromises.
...this is because of "async" and "returns" forms a mozpromise.
...And 5 more matches
NetUtil.jsm
method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attrib...
... methods asynccopy() the asynccopy() method performs a simple asynchronous copy of data from a source input stream to a destination output stream.
... nsiasyncstreamcopier asynccopy( asource, asink, acallback ); parameters asource the input stream from which to read the source data.
...And 5 more matches
Sqlite.jsm
all operations are asynchronous.
...all the functionality in sqlite.jsm is asynchronous.
... it is possible to automatically close the connection when the browser is closed with the shutdown hook: const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); try { sqlite.shutdown.addblocker("my connection closing", async () => await conn.close()); } catch (e) { // it's too late to block shutdown, just close the connection.
...And 5 more matches
Scroll-linked effects
however, most browsers now support some sort of asynchronous scrolling in order to provide a consistent 60 frames per second experience to the user.
... in the asynchronous scrolling model, the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the dom and fired on the main thread.
... below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: example 1: sticky positioning here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down.
...And 5 more matches
Promise.all() - JavaScript
an asynchronously resolved promise if the iterable passed contains no promises.
...this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject.
... see the example about "asynchronicity or synchronicity of promise.all" below.
...And 5 more matches
Promises - Archive of obsolete content
promise apis for common asynchronous operations due to the performance and stability costs of synchronous io, many apis which rely on it have been deprecated.
...these apis allow asynchronous operation to be achieved with a coding style similar to synchronous variants.
... the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code.
...And 4 more matches
RDF in Mozilla FAQ - Archive of obsolete content
if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it.
...var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions will not // be immediately available alternatively, you can create one directly using the xpcom component manager, as the following code fragment illustrates: // create an rdf/xml datasource using the xpcom component manager var ds = components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createinstance(components.interfaces.nsirdfdatasource); //...
...note that this will happen asynchronously.
...And 4 more matches
What is JavaScript? - Learn web development
async and defer there are actually two modern features we can use to bypass the problem of the blocking script — async and defer (which we saw above).
... scripts loaded using the async attribute (see below) will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading.
...it is best to use async when the scripts in the page run independently from each other and depend on no other script on the page.
...And 4 more matches
Message manager overview
its most important functions and attributes are: childcount : contains the number of children (typically, browser windows) getchildat() : get the child at the given index loadframescript() : load a frame script into every tab in the browser broadcastasyncmessage() : send a message to frame scripts addmessagelistener() : start listening to a specific message from all frame scripts removemessagelistener() : stop listening to a specific message interfaces nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster how to access access it using components.classes: // chrome s...
... its most important functions and attributes are: childcount : contains the number of children (typically, browser tabs) getchildat() : get the child at the given index loadframescript() : load a frame script into every tab in this window broadcastasyncmessage() : send a message to all frame scripts in this window addmessagelistener() : start listening to a specific message from frame scripts removemessagelistener() : stop listening to a specific message interfaces nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster how to access you can access it as a property of the...
... its most important functions are: loadframescript() : load a frame script into this browser frame (tab) sendasyncmessage() : send a message to all frame scripts in this browser frame addmessagelistener() : start listening to a specific message from frame scripts removemessagelistener() : stop listening to a specific message interfaces nsiprocesschecker nsiframescriptloader nsimessagelistenermanager nsimessagesender how to access the browser m...
...And 4 more matches
Performance
do some work on the window } function dosomething(message) { result = helper(content, message.data) sendasyncmessage("my-addon:response-from-child", {something: result}) } addmessagelistener("my-addon:request-from-parent", dosomething) why is this bad?
...do some work on the window } function dosomething(message) { frameglobal = message.target result = helper(frameglobal.content, message.data) frameglobal.sendasyncmessage("my-addon:response-from-child", {something: result}) } function addframe(frameglobal) { frameglobal.addmessagelistener("my-addon:request-from-parent", dosomething) } javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless callbacks.
... store heavyweight state once per process bad: // addon.js var main = new myaddonservice(); main.onchange(statechange); function statechange() { services.mm.broadcastasyncmessage("my-addon:update-configuration", {newconfig: main.serialize()}) } // framescript.js var maincopy; function onupdate(message) { maincopy = myaddonservice.deserialize(message.data.newconfig); } addmessagelistener("my-addon:update-configuration", onupdate) // maincopy used by other functions the main issue here is that a separate object is kept for each tab.
...And 4 more matches
nsIDNSService
method overview nsicancelable asyncresolve(in autf8string ahostname, in unsigned long aflags, in nsidnslistener alistener, in nsieventtarget alistenertarget); void init(); obsolete since gecko 1.8 nsidnsrecord resolve(in autf8string ahostname, in unsigned long aflags); void shutdown(); obsolete since gecko 1.8 attributes attribute type description myhostname autf8string ...
... constants resolve flag constants various flags that may be ored together to form the aflags parameter passed to asyncresolve() and resolve().
... resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be returned by asyncresolve() and resolve().
...And 4 more matches
HTMLScriptElement - Web APIs
htmlscriptelement.async htmlscriptelement.defer the async and defer attributes are boolean attributes that control how the script should be executed.
... the defer and async attributes must not be specified if the src attribute is absent.
... there are three possible execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads.
...And 4 more matches
Web Locks API - Web APIs
the web locks api allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it.
... work is done while holding the lock in an asynchronous task.
... navigator.locks.request('my_resource', async lock => { // the lock has been acquired.
...And 4 more matches
await - JavaScript
it can only be used inside an async function.
... description the await expression causes async function execution to pause until a promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.
... function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); console.log(x); // 10 } f1(); thenable objects thenable objects will be fulfilled just the same.
...And 4 more matches
File I/O - Archive of obsolete content
var file = url.queryinterface(components.interfaces.nsifileurl).file; // file is a nsifile to load from file://, http://, chrome://, resource:// and other urls directly, use xmlhttprequest or netutil.asyncfetch().
...so therefore for the first parameter, file, you can pass an nsifile object or a string (such as a jar path) see: netutil.asyncfetch: components.utils.import("resource://gre/modules/netutil.jsm"); netutil.asyncfetch(file, function(inputstream, status) { if (!components.issuccesscode(status)) { // handle error!
...var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.asyncfetch(channel, function(inputstream, status) { ...
...And 3 more matches
Error codes returned by Mozilla APIs
ns_binding_failed (0x804b0001) ns_binding_aborted (0x804b0002) the asynchronous request failed because it was aborted by some user action.
... ns_binding_redirected (0x804b0003) the asynchronous request has been "redirected" to a different async request.
... ns_binding_retargeted (0x804b0004) the asynchronous request has been "retargeted" to a different "handler." this error code is used with load groups to notify the load group observer when a request in the load group is removed from the load group and added to a different load group.
...And 3 more matches
Cross Process Object Wrappers
chrome to content messaging must be asynchronous.
... converting synchronous code to be asynchronous can be difficult and time-consuming.
... passing cpows from frame scripts frame scripts can send messages to chrome using one of two global functions: sendasyncmessage() or sendsyncmessage().
...And 3 more matches
Task.jsm
the task.jsm javascript code module implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
... method overview function async(atask); promise spawn(atask); properties attribute type description result read only constructor constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value.
...; return "value"; } methods async() create and return an "async function" that starts a new task.
...And 3 more matches
SavedFrame
asynccause if this stack frame is the asyncparent of other stack frames, then this is a string representing the type of asynchronous call by which this frame invoked its children.
... for example, if this frame’s children are calls to handlers for a promise this frame created, this frame’s asynccause would be "promise".
... if the asynchronous call was started in a descendant frame to which the requester of the property does not have access, this will be the generic string "async".
...And 3 more matches
mozIStorageStatement
indint32parameter(in unsigned long aparamindex, in long avalue); void bindint64parameter(in unsigned long aparamindex, in long long avalue); void bindnullparameter(in unsigned long aparamindex); void bindblobparameter(in unsigned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); mozistoragependingstatement executeasync(mozistoragestatementcallback acallback); boolean executestep(); boolean step(); void execute(); attributes attribute type description columncount unsigned long number of columns returned.
... newbindingparamsarray() creates and returns a new mozistoragebindingparamsarray object that can be used to bind multiple values to parameters in preparation for calling executeasync().
... bindparameters() binds all the parameters in the specified array to the statement in preparation for calling executeasync().
...And 3 more matches
nsIAuthPromptCallback
netwerk/base/public/nsiauthpromptcallback.idlscriptable interface for callback methods for the asynchronous nsiauthprompt2 method.
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) callers must call exactly one method if nsiauthprompt2.asyncpromptauth() returns successfully.
... they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns.
...And 3 more matches
nsICacheSession
netwerk/cache/public/nsicachesession.idlscriptable handles open synchronous and asynchronous cache entry operations along with evicting cache entries and checking for cache devices instantiation according to the session storage policies.
... inherits from: nsisupports last changed in gecko 14 (firefox 14 / thunderbird 14 / seamonkey 2.11) method overview void asyncopencacheentry(in acstring key, in nscacheaccessmode accessrequested, in nsicachelistener listener, [optional] in boolean nowait); void evictentries(); prbool isstorageenabled(); nsicacheentrydescriptor opencacheentry(in acstring key, in nscacheaccessmode accessrequested, in boolean blockingmode); void doomentry(in acstring key, in nsicachelistener listener); attributes attribute type description doomentriesifexpired prbool expired entries will be doomed or evicted if this attribute is set to true.
... methods asyncopencacheentry() this method gives an asynchronous cache access.
...And 3 more matches
nsIChannelEventSink
starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously.
... method overview void asynconchannelredirect(in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags, in nsiasyncverifyredirectcallback callback); void onchannelredirect(in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags); obsolete since gecko 2.0 constants constant value description redirect_temporary 1 << 0 this is a temporary redirect.
... methods asynconchannelredirect() called when a redirect occurs.
...And 3 more matches
nsIResumableChannel
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void asyncopenat(in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid); obsolete since gecko 1.8 void resumeat(in unsigned long long startpos, in acstring entityid); attributes attribute type description entityid acstring the entity id for this uri.
... methods asyncopenat() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) open this channel, and read starting at the specified offset.
...void asyncopenat( in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid ); parameters listener as for asyncopen.
...And 3 more matches
nsIServerSocket
void close(); void asynclisten(in nsiserversocketlistener alistener); prnetaddr getaddress();native code only!
... methods asynclisten() this method puts the server socket in the listening state.
... it will asynchronously listen for and accept client connections.
...And 3 more matches
LockManager.request() - Web APIs
examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback.
... await navigator.locks.request('my_resource', async lock => { // the lock was granted.
... async function do_read() { await navigator.locks.request('my_resource', {mode: 'shared'}, async lock => { // read code here.
...And 3 more matches
Using Service Workers - Web APIs
the below graphic shows a summary of the available service worker events: promises promises are a great mechanism for running async operations, with success dependant on one another.
... let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.
... sync try { const value = myfunction(); console.log(value); } catch(err) { console.log(err); } async myfunction().then((value) => { console.log(value); }).catch((err) => { console.log(err); }); in the first example, we have to wait for myfunction() to run and return value before any more of the code can execute.
...And 3 more matches
WebGL best practices - Web APIs
(this is okay for read buffers in conjunction with fences - see async data readback below.) readpixels() to the cpu (i.e.
...instead, use gpu-gpu readpixels in conjunction with async data readback.
... non-blocking async data download/readback the approach in webgl 2 is analogous to the approach in opengl: https://jdashg.github.io/misc/async-gpu-downloads.html function clientwaitasync(gl, sync, flags, interval_ms) { return new promise((resolve, reject) => { function test() { const res = gl.clientwaitsync(sync, flags, 0); if (res == gl.wait_failed) { reject(); return; } ...
...And 3 more matches
Promise.prototype.then() - JavaScript
return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop).
... following, an example to demonstrate the asynchronicity of the then method.
... // using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack.
...And 3 more matches
Performance best practices for Firefox front-end engineers
we could do it this way: async function nodeisdisplaynone(node) { let display = await window.promisedocumentflushed(() => { // do _not_ under any circumstances write to the dom in one of these // callbacks!
... here's an example: async function matchwidth(elem, otherelem) { let width = await window.promisedocumentflushed(() => { // do _not_ under any circumstances write to the dom in one of these // callbacks!
... indexeddb is preferable, as the api is asynchronous (all disk operations occur off of the main thread), and can be accessed from web workers.
...And 2 more matches
Necko Architecture
receiving data & nsistreamlistener you can read or write, from or to a channel using either the synchronous api, or the asynchronous api.
... if you want to move data asynchronously you need to be able to receive callbacks using an implementation of nsistreamlistener.
...if you initiate an asynchronous transfer, you receive callbacks that notify you when things are happening.
...And 2 more matches
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
there are two ways of getting the input stream: by calling the channel's .open() method for a synchronous read, or by calling the channel's .asyncopen() method with an nsistreamlistener object.
... netutil.jsm provides apis for copying an input stream to an output stream (the asynccopy() method), getting an input stream from another source (the asyncfetch() method), and reading an input stream into a string (the readinputstreamtostring() method).
...most streams are asynchronous: they make no assumptions that all the data a resource provides is available immediately.
...And 2 more matches
nsIMicrosummaryService
the set might change after this method returns, since this method will trigger an asynchronous load of the page in question (if it isn't already loaded) to see if it references any page-specific microsummaries.
... if the caller passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when callers want to display a list of microsummaries for a page that isn't loaded, and they want to display the actual content of the selected microsummary immediately (rather than after the content is asynchronously loaded).
...otherwise, it'll asynchronously download the necessary information (the generator and/or page) before refreshing the microsummary.
...And 2 more matches
nsIPipe
inherits from: nsisupports last changed in gecko 1.6 method overview void init(in boolean nonblockinginput, in boolean nonblockingoutput, in unsigned long segmentsize, in unsigned long segmentcount, in nsimemory segmentallocator); attributes attribute type description inputstream nsiasyncinputstream the pipe's input end, which also implements nsisearchableinputstream.
... outputstream nsiasyncoutputstream the pipe's output end.
...this example presumes that the pipe is being filled asynchronously on some background thread.
...And 2 more matches
nsIProcess
s = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); method overview void init(in nsifile executable); void initwithpid(in unsigned long pid); obsolete since gecko 1.9.2 void kill(); void run(in boolean blocking, [array, size_is(count)] in string args, in unsigned long count); void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); void runw(in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count); void runwasync([array, size_is(count)] in wstring args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); ...
... runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running.
... void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set.
...And 2 more matches
nsIProgressEventSink
netwerk/base/public/nsiprogresseventsink.idlscriptable this interface is used to asynchronously convey channel status and progress information that is generally not critical to the processing of the channel.
... inherits from: nsisupports last changed in gecko 1.7 this interface is used to asynchronously convey channel status and progress information that is generally not critical to the processing of the channel.
...the channel will begin passing notifications to the progress event sink after its asyncopen method has been called.
...And 2 more matches
nsIWebSocketChannel
to create an instance, use: var websocketchannel = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiwebsocketchannel); method overview void asyncopen(in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext); void close(in unsigned short acode, in autf8string areason); void sendbinarymsg(in acstring amsg); void sendmsg(in autf8string amsg); attributes attribute type description extensions acstring sec-websocket-extensions response header v...
... methods asyncopen() asynchronously opens the websocket connection.
...the socket listener's methods are called on the thread that calls asyncopen() and are not called until after asyncopen() returns.
...And 2 more matches
Waterfall - Firefox Developer Tools
if this is inside a callback from a promise, this will also show the "async stack".
...in the screenshot below, we've zoomed in on a js function that's caused a drop in the frame rate: the intensive javascript article shows how the waterfall can highlight responsiveness problems caused by long javascript functions, and how you can use asynchronous methods to keep the main thread responsive.
... async stack new in firefox 41.
...And 2 more matches
ContentIndex - Web APIs
// reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
... // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelem...
...And 2 more matches
Content Index API - Web APIs
// reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
... // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelem...
...And 2 more matches
File and Directory Entries API - Web APIs
two very similar apis exist depending on whether you desire asynchronous or synchronous behavior.
...the asynchronous api will not block and functions and the api will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives.
... asynchronous api the asynchronous api should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread.
...And 2 more matches
Using IndexedDB - Web APIs
about this document this tutorial walks you through using the asynchronous api of indexeddb.
...this article documents the types of objects used by indexeddb, as well as the methods of the asynchronous api (the synchronous api was removed from spec).
...most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or error.
...And 2 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
note: this example makes use of modern javascript features including async functions and the await expression.
... async function enablehold(audiostream) { try { await audiotransceiver.sender.replacetrack(audiostream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled = false; audiotransceiver.direction = "sendonly"; } catch(err) { /* handle the error */ } } the three lines of code within the try block perform the following steps: replace their outgoing audio track with a mediast...
... async function holdrequested(offer) { try { await peerconnection.setremotedescription(offer); await audiotransceiver.sender.replacetrack(null); audiotransceiver.direction = "recvonly"; await sendanswer(); } catch(err) { /* handle the error */ } } the steps taken here are: set the remote description to the specified offer by calling rtcpeerconnection.setremotedescription()...
...And 2 more matches
Using XMLHttpRequest - Web APIs
function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://www.example.org/example.txt"); oreq.send(); types of requests a request made via xmlhttprequest can fetch the data in one of two ways, asynchronously or synchronously.
... the type of request is dictated by the optional async argument (the third argument) that is set on the xmlhttprequest.open() method.
... if this argument is true or not specified, the xmlhttprequest is processed asynchronously, otherwise the process is handled synchronously.
...And 2 more matches
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
asynchtml5 for classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.
... for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.
...see also async scripts for asm.js.
...And 2 more matches
Promise() constructor - JavaScript
the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typically, some asynchronous operation.
...the side-effect is that the promiseobj becomes "resolved." typically, it works like this: the operation within executor is asynchronous and provides a callback.
... the promiseobj (asynchronously) invokes any .then() associated with it.
...And 2 more matches
Promise.any() - JavaScript
an asynchronously resolved promise if the iterable passed contains no promises.
...this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected.
... fulfilment if any of the passed-in promises fulfil, the returned promise asynchronously fulfils with the value of the promise that fulfilled, whether or not the other promises have fulfilled or rejected.
...And 2 more matches
Connecting to Remote Content - Archive of obsolete content
;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.onerror = function(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode.
... request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not.
... in asynchronous mode code execution continues immediately after the send call.
...therefore, it is very important that xmlhttprequest calls are always done asynchronously.
Performance best practices in extensions - Archive of obsolete content
use asynchronous i/o this cannot be stressed enough: never do synchronous i/o on the main thread.
... netutils.jsm provides helpers for asynchronous reading and copying of files.
...use the asynchronous api instead.
... performing sequential, asynchronous operations can often be greatly simplified using promises.
Index - MDN Web Docs Glossary: Definitions of Web-related terms
14 ajax ajax, codingscripting, glossary, infrastructure, l10n:priority ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
... 24 asynchronous glossary, web, webmechanics, asynchronous the term asynchronous refers to or multiple related things happening without waiting for the previous one to complete).
... 335 promise glossary, promise, promises, asynchronous a promise is an object that's returned by a function that has not yet completed its work.
... 456 thread glossary, thread, asynchronous thread in computer science is the execution of running multiple tasks or programs at the same time.
Fetching data from the server - Learn web development
note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data.
...add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown.
... fetch the fetch api is basically a modern replacement for xhr; it was introduced in browsers recently to make asynchronous http requests easier to do in javascript, both for developers and other apis that build on top of fetch.
... after that, you can see the .then() method chained onto the end of fetch() — this method is a part of promises, a modern javascript feature for performing asynchronous operations.
Message manager overview
communicate with frame scripts using addmessagelistener() and broadcastasyncmessage() or sendasyncmessage() functions.
... broadcastasyncmessage() sends the message to every <browser> in every browser window.
.../ chrome script let globalmm = cc["@mozilla.org/globalmessagemanager;1"] .getservice(ci.nsimessagelistenermanager); window message manager the window message manager is associated with a specific browser window, and operates on every <browser> (that is, every content tab) loaded into that window: loadframescript() loads the given script into every <browser> in that browser window broadcastasyncmessage() sends the message to every <browser> in that browser window.
...elistenermanager nsimessagebroadcaster the window message manager can be accessed as a property of the browser window: // chrome script let windowmm = window.messagemanager; browser message manager the browser message manager is specific to a single xul <browser> element (which essentially corresponds to a single tab): loadframescript() loads the given script only into its <browser> sendasyncmessage() sends the message only to that <browser>.
How to implement a custom autocomplete search component
queryinterface: xpcomutils.generateqi([ ci.nsiautocompleteresult ]) }; /** * @constructor * * @implements {nsiautocompletesearch} */ function providerautocompletesearch() { } providerautocompletesearch.prototype = { classid: class_id, classdescription : class_name, contractid : contract_id, /** * searches for a given string and notifies a listener (either synchronously * or asynchronously) of the result * * @param searchstring the string to search for * @param searchparam an extra parameter * @param previousresult a previous result to use for faster searchinig * @param listener the listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, previousresult, listener) { var results = ['mary', 'john']; var au...
...tocomplete_result = new providerautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, null); listener.onsearchresult(this, autocomplete_result); }, /** * stops an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompletesearch ]) }; // the following line is what xpcom uses to create components const nsgetfactory = xpcomutils.generatensgetfactory([ providerautocompletesearch ]); then register your xpcom component.
... queryinterface: function(aiid) { if (!aiid.equals(ci.nsiautocompleteresult) && !aiid.equals(ci.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; // implements nsiautocompletesearch function simpleautocompletesearch() { } simpleautocompletesearch.prototype = { /* * search for a given string and notify a listener (either synchronously * or asynchronously) of the result * * @param searchstring - the string to search for * @param searchparam - an extra parameter * @param previousresult - a previous result to use for faster searchinig * @param listener - a listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, result, listener) { // this autocomplete source assumes the deve...
...push(searchresults[i].value); if (searchresults[i].comment) comments.push(searchresults[i].comment); else comments.push(null); } } var newresult = new simpleautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, comments); listener.onsearchresult(this, newresult); } }, /* * stop an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: function(aiid) { if (!aiid.equals(ci.nsiautocompletesearch) && !aiid.equals(ci.nsisupports)) throw components.results.ns_error_no_interface; return this; } }; // factory var simpleautocompletesearchfactory = { singleton: null, createinstance: function (aouter, aiid) { if (aouter !
DeferredTask.jsm
this is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function.
... set up a function or an asynchronous task whose execution can be triggered after a defined delay.
... a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught exception will be reported.
... for example, during shutdown, you may want to ensure that any pending write is processed, using the latest version of the data if the timer is armed: asyncshutdown.profilebeforechange.addblocker( "example service: shutting down", () => savedeferredtask.finalize() ); instead, if you are going to delete the saved data from disk anyways, you might as well prevent any pending write from starting, while still ensuring that any write that is currently in progress terminates, so that the file is not in use any more: savedeferredtask.disarm(); savede...
L20n Javascript API
ed, deflocale) { return intl.prioritizelocales(available, requested, deflocale); }); negotiator is a function which takes the following arguments: available - all locales available to the context instance, requested - locales preferred by the user, deflocale - the default locale to be used as the ultimate fallback, callback - the function to call when the negotiation completes (useful for asynchronous negotiators).
... it must return an array which is the final fallback chain of locales, or if the negotiation is asynchronous, it must return a falsy value and call the callback argument upon completion.
... the final list of locales supported by the context instance will be negotiated asynchronously by the negotiator registered by registerlocalenegotiator.
...it will be called when the entities become available (asynchronously) or whenever the translation of any of the entities changes.
Components.isSuccessCode
however, if you are using asynchronous apis, it may be essential.
... for example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed.
... note: nsiasyncstreamcopier.init() has changed in gecko 1.9.2, omit last 2 boolean parameters if you're using gecko 1.9.1 and earlier.
... if (!components.issuccesscode(statuscode)) copyfailed = true; }, queryinterface: function(aiid) { if (aiid.equals(ci.nsirequestobserver) || aiid.equals(ci.nsisupports)) return this; throw cr.ns_error_no_interface; } }; var copier = cc["@mozilla.org/network/async-stream-copier;1"] .createinstance(ci.nsiasyncstreamcopier); copier.init(instream, outstream, null, true, false, 8192, true, true); copier.asynccopy(copyobserver, null); } ...
mozIVisitInfoCallback
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides callback handling functionality for moziasynchistory.updateplaces() 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) method overview void handleerror(in nsresult aresultcode, in moziplaceinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handleerror() called when a moziplaceinfo couldn't be processed.
... handleresult() called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces().
... oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces().
...see also mozivisitinfo moziasynchistory ...
nsIAuthPrompt2
it can be used to prompt users for authentication information, either synchronously or asynchronously.
...to create an instance, use: var authprompt2 = components.classes["@mozilla.org/login-manager/prompter;1"] .createinstance(components.interfaces.nsiauthprompt2); method overview nsicancelable asyncpromptauth(in nsichannel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo); boolean promptauth(in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo); constants constant value description level_none 0 the password will be sent unencrypted.
... methods asyncpromptauth() asynchronously prompt the user for a username and password.
... nsicancelable asyncpromptauth( in nsichannel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo ); parameters achannel the channel that requires authentication.
nsIFeedProcessor
to create an instance, use: var feedprocessor = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); method overview void parseasync(in nsirequestobserver requestobserver, in nsiuri uri); void parsefromstream(in nsiinputstream stream, in nsiuri uri); void parsefromstring(in astring str, in nsiuri uri); attributes attribute type description listener nsifeedresultlistener the feed result listener that will respond to feed events.
... methods parseasync() parses a feed asynchronously.
...you must not call any of the other parsing methods on the nsifeedprocessor interface during an asynchronous parse.
... void parseasync( in nsirequestobserver requestobserver, in nsiuri uri ); parameters requestobserver the observer to be notified when parsing starts and stops.
nsIHttpUpgradeListener
method overview void ontransportavailable(in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout); methods ontransportavailable() called when an http protocol upgrade attempt is completed, passing in the information needed by the protocol handler to take over the channel that is no longer being used by http.
...void ontransportavailable( in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout ); parameters atransport the nsisockettransport describing the socket connection between the browser and the server; this socket can now be used for the new protocol instead of http.
... asocketin the nsiasyncinputstream object representing the input stream for data coming from the server over the socket connection.
... asocketout the nsiasyncoutputstream object representing the out stream for sending data to the server over the socket.
nsIInputStreamCallback
xpcom/io/nsiasyncinputstream.idlscriptable this is a companion interface for nsiasyncinputstream.asyncwait().
... inherits from: nsisupports last changed in gecko 1.7 method overview void oninputstreamready(in nsiasyncinputstream astream); methods oninputstreamready() called to indicate that the stream is either readable or closed.
... void oninputstreamready( in nsiasyncinputstream astream ); parameters astream the stream whose nsiasyncinputstream.asyncwait() method was called.
... see also nsiasyncinputstream.asyncwait() ...
nsIProtocolProxyCallback
netwerk/base/public/nsiprotocolproxycallback.idlscriptable this interface serves as a closure for nsiprotocolproxyservice.asyncresolve().
...void onproxyavailable( in nsicancelable arequest, in nsiuri auri, in nsiproxyinfo aproxyinfo, in nsresult astatus ); parameters arequest the value returned from asyncresolve.
... auri the uri passed to asyncresolve.
...the value returned from asyncresolve.
nsIRequest
this will close any open input or output streams and terminate any async requests.
...similarly, removal from the load group (if any) must also happen asynchronously.
...ispending is true when there is an outstanding asynchronous event that will make the request no longer be pending.
... requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsichannel implementations are only pending once asyncopen returns successfully).
nsIStreamConverter
asynchronous: nsistreamlistener to nsistreamlistener.
...stream converter contractid format (the stream converter root key is defined in this file): @mozilla.org/streamconv;1?from=from_mime_type&to=to_mime_type method overview void asyncconvertdata(in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert(in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt); methods asyncconvertdata() asynchronous version: converts data arriving via the converter's nsistreamlistener.ondataavailable() method from one type to another, ...
...use this method when you want to proxy (and convert) nsistreamlistener callbacks asynchronously.
... void asyncconvertdata( in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt ); parameters afromtype the mime type of the original/raw data.
nsISupports proxies
xpcom proxies were a technology which allowed code to make asynchronous or synchronous xpcom calls to a different thread on arbitrary xpcom interfaces.
... the proxytype parameter can be either two flags: proxy_sync or proxy_async.
... proxy_async, on the other hand, is a "fire and forget" method call.
... warning about proxy_async: you must take very special care when using this flag.
URLs - Plugins
note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data.
... npn_geturlnotify handles the url request asynchronously.
... npn_posturl is typically asynchronous: it returns immediately and only later handles the request and calls npp_notify (which, in turn, calls npp_urlnotify).
...npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify.
Console messages - Firefox Developer Tools
async stack frames stack traces show stack frames for async functions separately from those for synchronous functions.
... when you run code containing an async function, its traces (console.trace or thrown error) are shown with an async: prefix.
... synchronous and asynchronous reflows if a change is made that invalidates the current layout — for example, the browser window is resized or some javascript modifies an element's css — the layout is not recalculated immediately.
... instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints).
Using Fetch - Web APIs
it also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
... // example post method implementation: async function postdata(url = '', data = {}) { // default options are marked with * const response = await fetch(url, { method: 'post', // *get, post, put, delete, etc.
... async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder('utf-8'); const response = await fetch(fileurl); const reader = response.body.getreader(); let { value: chunk, done: readerdone } = await reader.read(); chunk = chunk ?
...utf8decoder.decode(chunk) : ''); startindex = re.lastindex = 0; continue; } yield chunk.substring(startindex, result.index); startindex = re.lastindex; } if (startindex < chunk.length) { // last line didn't end in a newline char yield chunk.substr(startindex); } } async function run() { for await (let line of maketextfilelineiterator(urloffile)) { processline(line); } } run(); checking that the fetch was successful a fetch() promise will reject with a typeerror when a network error is encountered or cors is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for exa...
IDBRequest - Web APIs
the idbrequest interface of the indexeddb api provides access to results of asynchronous requests to databases and database objects using event handler attributes.
... all asynchronous operations immediately return an idbrequest instance.
... in plain words, all asynchronous methods return a request object.
... example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases.
IndexedDB API - Web APIs
learn to use indexeddb asynchronously from first principles with our using indexeddb guide.
... synchronous and asynchronous operations performed using indexeddb are done asynchronously, so as not to block applications.
... indexeddb originally included both synchronous and asynchronous apis.
...this method returns an idbrequest object; asynchronous operations communicate to the calling application by firing events on idbrequest objects.
Navigator.sendBeacon() - Web APIs
the navigator.sendbeacon() method asynchronously sends a small amount of data over http to a web server.
... ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous xmlhttprequests made in an unload handler.
...with the sendbeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation.
... this solves all of the problems with submission of analytics data: the data is sent reliably it's sent asynchronously it doesn't impact the loading of the next page in addition, the code is simpler to write than any of the older techniques!
PaymentResponse.retry() - Web APIs
async function handlepayment() { const payrequest = new paymentrequest(methoddata, details, options); try { let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the except...
...} async function dopaymentrequest() { const request = new paymentrequest(methoddata, details, options); const response = await request.show(); await recursivevalidate(request, response); await response.complete("success"); } // keep validating until the data looks good!
... async function recursivevalidate(request, response) { const promisestofixthings = []; const errors = await validate(request, response); if (!errors) { return; } if (errors.shippingaddress) { // "shippingaddresschange" fired at request object const promise = fixfield(request, "shippingaddresschange", shippingvalidator); promisestofixthings.push(promise); } if (errors.payer) { // "payerdetailchange" fired at response object const promise = fixfield(response, "payerdetailchange", payervalidator); promisestofixthings.push(promise); } await promise.all([response.retry(errors), ...promisestofixthings]); await recursivevalidate(request, response); } function fixfield(requestorresponse, event, validator) { return new promise(resolve => { // browse...
... requestorresponse.addeventlistener(event, async function listener(ev) { const promisetovalidate = validator(requestorresponse); ev.updatewith(promisetovalidate); const errors = await promisetovalidate; if (!errors) { // yay!
SubtleCrypto.exportKey() - Web APIs
*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button.
...*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "pkcs8", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin private key-----\n${exportedasbase64}\n-----end private key-----`; const exportkeyoutput = document.queryselector(".exported-key"); exportkeyo...
...*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "spki", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin public key-----\n${exportedasbase64}\n-----end public key-----`; const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutp...
...*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "jwk", key ); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = json.stringify(exported, null, " "); } /* generate a sign/verify key pair, then set up an event listener on the "export" button.
SubtleCrypto.unwrapKey() - Web APIs
*/ async function getunwrappingkey() { // 1.
...*/ async function unwrapsecretkey(wrappedkey) { // 1.
...*/ async function getunwrappingkey() { // 1.
...*/ async function unwrapprivatekey(wrappedkey) { // 1.
SubtleCrypto.verify() - Web APIs
*/ async function verifymessage(publickey) { const signaturevalue = document.queryselector(".rsassa-pkcs1 .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( "rsassa-pkcs1-v1_5", publickey, signature, encoded ); signaturevalue.classlist.add(result ?
...*/ async function verifymessage(publickey) { const signaturevalue = document.queryselector(".rsa-pss .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( { name: "rsa-pss", saltlength: 32, }, publickey, signature, encoded ); signaturevalue.classlist.add(resu...
...*/ async function verifymessage(publickey) { const signaturevalue = document.queryselector(".ecdsa .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( { name: "ecdsa", hash: {name: "sha-384"}, }, publickey, signature, encoded ); signaturevalue.classlist.add...
...*/ async function verifymessage(key) { const signaturevalue = document.queryselector(".hmac .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( "hmac", key, signature, encoded ); signaturevalue.classlist.add(result ?
SubtleCrypto.wrapKey() - Web APIs
*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it.
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); iv = window.crypto.getrandomvalues(new uint8array(12)); return window.crypto.subtle.wrapkey( "pkcs8", keytowrap, wrappingkey, { name: "aes-gcm"...
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); iv = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.wrapkey( "spki", keytowrap, wrappingkey, { name: "aes-cbc",...
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); iv = window.crypto.getrandomvalues(new uint8array(12)); return window.crypto.subtle.wrapkey( "jwk", keytowrap, wrappingkey, { name: "aes-gcm", ...
Starting up and shutting down a WebXR session - Web APIs
so a more complete function that starts up and returns a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } this function returns the new xrsession or throws an exception if an error occurs while creating the session.
... for example, if you need an unbounded reference space, you can specify that as a required feature in order to ensure that the session you get can use unbounded spaces: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr", { requiredfeatures: [ "unbounded" ] }); return session; } catch(error) { throw error; } } on the other hand, if you need aninline session and would prefer a local reference space, you can do this: async function createinlinesession(xr) { try { session = await xr.reque...
... in basic form, code to do this final setup might look something like this: async function runsession(session) { let worlddata; session.addeventlistener("end", onsessionend); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); // set up webgl data and such worlddata = loadglprograms(session, "worlddata.xml"); if (!worlddata) { return null; } // finish configuring webgl worlddata.session.updateren...
... async function shutdownxr(session) { if (session) { await session.end(); /* at this point, webxr is fully shut down */ } } when shutdownxr() returns to its caller, the webxr session is fully and safely shut down.
Getting Started - Developer guides
ajax stands for asynchronous javascript and xml.
...ajax’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
... the optional third parameter sets whether the request is asynchronous.
...you have two options to access that data: httprequest.responsetext – returns the server response as a string of text httprequest.responsexml – returns the response as an xmldocument object you can traverse with javascript dom functions note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true).
Method definitions - JavaScript
syntax const obj = { get property() {}, set property(value) {}, property( parameters… ) {}, *generator( parameters… ) {}, async property( parameters… ) {}, async* generator( parameters… ) {}, // with computed keys get [property]() {}, set [property](value) {}, [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, async* [generator]( parameters… ) {}, }; description the shorthand syntax is similar to the getter and setter syntax introduced in ecma...
... // using a named property const obj2 = { g: function* () { let index = 0 while (true) { yield index++ } } }; // the same object using shorthand syntax const obj2 = { * g() { let index = 0 while (true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it.next().value) // 1 async methods async methods can also be defined using the shorthand syntax.
... // using a named property const obj3 = { f: async function () { await some_promise } } // the same object using shorthand syntax const obj3 = { async f() { await some_promise } } async generator methods generator methods can also be async.
... const obj4 = { f: async function* () { yield 1 yield 2 yield 3 } }; // the same object using shorthand syntax const obj4 = { async* f() { yield 1 yield 2 yield 3 } } method definitions are not constructable methods cannot be constructors!
Web Performance
it is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience.
...instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible.
... beacon api the beacon interface schedules an asynchronous and non-blocking request to a web server.
... intersection observer api learn to time element visibility with the intersection observer api and be asynchronously notified when elements of interest becomes visible.
Updating addons broken by private browsing changes - Archive of obsolete content
if your code refers to any of the following interfaces: ff 15: nsidomstoragemanager ff 16: nsitransferable ff 18: imgicache moziasyncfavicons nsifaviconservice nsiwebbrowserpersist ff 19: nsicontentprefservice nsidownloadmanager nsidownload nsihttpauthmanager nsistricttransportsecurityservice ff 20: nsiprivatebrowsingservice nsirecentbadcertservice furthermore, if your code uses any of these common chrome apis: ff 19: saveurl saveinternal openlinkin ff 20: openbrowserwindow gprivatebrowsingui finally, if your code watch...
... moziasyncfavicons/nsifaviconservice: setandfetchfaviconforpage/setandloadfaviconforpage now take a required privacy status argument, either nsifaviconservice.favicon_load_private or nsifaviconservice.favicon_load_non_private.
... nsidownload's getdownload method is deprecated; use the asynchronous getdownloadbyguid method instead.
Notes on HTML Reflow - Archive of obsolete content
other reflows are incremental and are dealt with asynchronously; for example, when content streams in from the network.
... incremental reflows are dispatched en masse when the presentation shell's incremental reflow queue is asynchronously serviced.
...instead, it queues the command, and processes it asynchronously along with other queued reflow commands en masse .
jspage - Archive of obsolete content
on(b,a){return math.pow(2,10*--b)*math.cos(20*b*math.pi*(a[0]||1)/3);}});["quad","cubic","quart","quint"].each(function(b,a){fx.transitions[b]=new fx.transition(function(c){return math.pow(c,[a+2]); });});var request=new class({implements:[chain,events,options],options:{url:"",data:"",headers:{"x-requested-with":"xmlhttprequest",accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",issuccess:null,emulation:true,urlencoded:true,encoding:"utf-8",evalscripts:false,evalresponse:false,nocache:false},initialize:function(a){this.xhr=new browser.request(); this.setoptions(a);this.options.issuccess=this.options.issuccess||this.issuccess;this.headers=new hash(this.options.headers);},onstatechange:function(){if(this.xhr.readystate!=4||!thi...
..."){var c=(this.options.encoding)?"; charset="+this.options.encoding:""; this.headers.set("content-type","application/x-www-form-urlencoded"+c);}if(this.options.nocache){var f="nocache="+new date().gettime();g=(g)?f+"&"+g:f; }var e=b.lastindexof("/");if(e>-1&&(e=b.indexof("#"))>-1){b=b.substr(0,e);}if(g&&a=="get"){b=b+(b.contains("?")?"&":"?")+g;g=null;}this.xhr.open(a.touppercase(),b,this.options.async); this.xhr.onreadystatechange=this.onstatechange.bind(this);this.headers.each(function(m,l){try{this.xhr.setrequestheader(l,m);}catch(n){this.fireevent("exception",[l,m]); }},this);this.fireevent("request");this.xhr.send(g);if(!this.options.async){this.onstatechange();}return this;},cancel:function(){if(!this.running){return this; }this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$...
..."); b.send({data:this,url:a||b.options.url});return this;}});request.html=new class({extends:request,options:{update:false,append:false,evalscripts:true,filter:false},processhtml:function(c){var b=c.match(/<body[^>]*>([\s\s]*?)<\/body>/i); c=(b)?b[1]:c;var a=new element("div");return $try(function(){var d="<root>"+c+"</root>",g;if(browser.engine.trident){g=new activexobject("microsoft.xmldom"); g.async=false;g.loadxml(d);}else{g=new domparser().parsefromstring(d,"text/xml");}d=g.getelementsbytagname("root")[0];if(!d){return null;}for(var f=0,e=d.childnodes.length; f<e;f++){var h=element.clone(d.childnodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response; b.html=d.stripscripts(function(e){b.javascript=e;});var a=this.processhtm...
Audio for Web games - Game development
we can do this with javascript's async/await functionality.
... const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing.
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can call once a file has been fetched.
How do you set up a local testing server? - Learn web development
this can be due to a variety of reasons, the most likely being: they feature asynchronous requests.
... some browsers (including chrome) will not run async requests (see fetching data from the server) if you just run the example from a local file.
... running a simple local http server to get around the problem of async requests, we need to test such examples by running them through a local web server.
Sending forms through JavaScript - Learn web development
when the user tries to send the data, the application takes control and transmits the data asynchronously in the background, updating only the parts of the ui that require changes.
... sending arbitrary data asynchronously is generally called ajax, which stands for "asynchronous javascript and xml".
...window.addeventlistener( 'load', function () { // these variables are used to store the form data const text = document.getelementbyid( "thetext" ); const file = { dom : document.getelementbyid( "thefile" ), binary : null }; // use the filereader api to access file content const reader = new filereader(); // because filereader is asynchronous, store its // result when it finishes to read the file reader.addeventlistener( "load", function () { file.binary = reader.result; } ); // at page load, if a file is already selected, read it.
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
try this now: function onedit() { editing = true // enter editing mode settimeout(() => nameel.focus(), 0) // asynchronous call to set focus to name input } the above solution works, but it is rather inelegant.
... first of all, import tick at the top of the <script> section alongside your existing import: import { tick } from 'svelte' next, call tick() with await from an async function; update onedit() like so: async function onedit() { editing = true // enter editing mode await tick() nameel.focus() } if you try it now you'll see that everything works as expected.
... other actions improvements in the previous section, while working with the todo components, we had to deal with bind:this, tick(), and async functions just to give focus to our <input> as soon as it was added to the dom.
Handling common JavaScript problems - Learn web development
making sure asynchronous operations have returned before trying to use the values they return.
...a very common problem with async requests like this is when you try to do something with the response object before it has actually been returned from the network.
... for example: promises are a great new feature for performing asynchronous operations and making sure those operations are complete before code that relies on their results is used for something else.
Application cache implementation overview
updating an existing cache or first download of an offline cache the process of updating or first caching is invoked asynchronously from nscontentsink::processofflinemanifest() using nsofflinecacheupdateservice.
... the parallel load is implemented by asynchronous recursive calls to processnexturi(), a method searching always a single entry that is scheduled to load.
...processnexturi then invokes it self asynchronously via dispatch to a main thread when not already on the concurrency limit of 15 loads.
Creating Sandboxed HTTP Connections
io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's newchannelfromuri method: // get a channel for that nsiuri var channel = ioservice.newchannelfromuri(uri); to initiate the connection, the asyncopen method is called.
... channel.asyncopen(listener, null); http notifications the above mentioned listener is a nsistreamlistener, which gets notified about events such as http redirects and data availability.
...ents.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); // get a channel for that nsiuri gchannel = ioservice.newchannelfromuri(uri); // get an listener var listener = new streamlistener(callbackfunc); gchannel.notificationcallbacks = listener; gchannel.asyncopen(listener, null); function streamlistener(acallbackfunc) { this.mcallbackfunc = acallbackfunc; } streamlistener.prototype = { mdata: "", // nsistreamlistener onstartrequest: function (arequest, acontext) { this.mdata = ""; }, ondataavailable: function (arequest, acontext, astream, asourceoffset, alength) { var scriptableinputstream = components.classes["@mozilla.o...
Frame script loading and lifetime
var gcontentframemessagemanager = this; addeventlistener('unload', function(aevent) { if (aevent.target == gcontentframemessagemanager) { sendasyncmessage('my-addon-id', 'framescript-died'); // if you did not set third argument of `services.mm.addmessagelistener` to `true`, then this will fail to send a message } }, false); note about unload during uninstallation/upgrade when your add-on is uninstalled, or disabled, you should: cancel it, if you have used allowdelayedload, by calling removedelayedframescript; ensuring the frame scri...
... note: you might think that there is a race condition here due to the asynchronous nature of the message passing: your add-on is disabled for an upgrade.
... in fact, the message manager guarantees that loadframescript and broadcastasyncmessage are guaranteed to affect frame scripts in the order that they are called, so in this case "disable" will be received and consumed before the new frame scripts are loaded.
Download
the cancellation request is asynchronous.
...this behavior is designed for the case where the call to cancel happens asynchronously, and is consistent with the case where the cancellation request could not be processed in time.
...this is required because cancellation and other operations are asynchronous.
OS.File for the main thread
the content is read asynchronously.
...note that this snippet is useful as a demonstration of complex asynchronous programming with os.file – in most cases, function os.file.writeatomic is a better choice.
... let writestream = function writestream(data, outfile, chunksize) { let view = new uint8array(data); let loop = function loop(pos) { // define a recursive asynchronous loop.
Optimizing Applications For NSPR
on nt, this problem is especially obvious because the idle thread, which is in charge of driving the asynch io completion port, is also blocked.
...nspr does take advantage of macintosh' asynchronous i/o capability to perform scheduling during i/o.
... win-nt the win-nt port of nspr takes advantage of some of the features of nt that are not available in win-95, such as fibers and asynch i/o.
Necko Interfaces Overview
channel is used to download the resource once) download initiated via nsichannel::asyncopen method can be canceled via nsirequest::cancel method at anytime after invocation of asyncopen method nsiprotocolhandler a service that manages a protocol, identified by it's uri scheme (eg.
... http) maps uri string to nsiuri instance via newuri method creates nsichannel instance from nsiuri instance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consumer of a nsichannel instance passed to nsichannel::asyncopen method nsirequestobserver::onstartrequest - notifies start of async download nsistreamlistener::ondataavailable - notifies presence of downloaded data nsirequestobserver::onstoprequest - notifies completion of async download, possibly w/ error nsiloadgroup : nsirequest attribute of a nsirequest channel impl adds itself to its load group during invocation of asyncopen channel impl removes itself from its load group when download completes load groups in gecko own all channels used to load a particular page (until the channels co...
...mplete) all channels owned by a load group can be canceled at once via the load group's nsirequest::cancel method nsitransport represents a physical connection, such as a file descriptor or a socket used directly by protocol handler implementations (as well as by mailnews and chatzilla) synchronous i/o methods: openinputstream, openoutputstream asynchronous i/o methods: asyncread, asyncwrite nsitransport::asyncread takes a nsistreamlistener parameter original document information author(s): darin fisher last updated date: december 10, 2001 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
Multithreading in Necko
when a socket can be read, the socket's listener is notified either synchronously (on the same thread) or asynchronously via a nsistreamlistenerproxy impl.
...as with the socket transport thread, the nsistreamlistener passed to a file transport's asyncread method can operate partially on the file transport's thread before proxying data to the main thread.
...for example, on xp_win an invisible window is created with a message pump on a background thread for processing wsa asynchronous dns events.
Making cross-thread calls using runnables
in general, threading and message passing should be asynchronous.
...so we declare an asynchronous version of the same function: typedef void (*picallback)(const nscstring& result); // callback function void calculatepiasynchronously(int digits, picallback callback); creating a runnable nsrunnable is a helper class: it already implements threadsafe refcounting, so all you need to do is override the run() function.
...) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable = new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(...
nsIAccessibleEvent
event_asynch_show 0x0004 a hidden object is shown -- this is a layout occurrence and is thus asynchronous.
... event_asynch_hide 0x0005 an object is hidden -- this is a layout occurrence and is thus asynchronous.
... event_asynch_significant_change 0x0006 an object had a significant layout change which could affect the type of accessible object -- this is a layout occurrence and is thus asynchronous.
nsIFrameMessageManager
method overview void addmessagelistener(in astring amessage, in nsiframemessagelistener alistener, [optional] in boolean listenwhenclosed); void removemessagelistener(in astring amessage, in nsiframemessagelistener alistener); void sendasyncmessage(in astring amessage, in astring json); methods addmessagelistener() adds a message listener to the local frame.
... sendasyncmessage() asynchronously sends a message to the listeners.
... void sendasyncmessage( in astring amessage, in astring json ); parameters amessage the name of the message to send to the listeners.
nsIOutputStreamCallback
xpcom/io/nsiasyncoutputstream.idlscriptable this is a companion interface for nsiasyncoutputstream.asyncwait.
... inherits from: nsisupports last changed in gecko 1.7 method overview void onoutputstreamready(in nsiasyncoutputstream astream); methods onoutputstreamready() called to indicate that the stream is either writable or closed.
... void onoutputstreamready( in nsiasyncoutputstream astream ); parameters astream the stream whose nsiasyncoutputstream.asyncwait() method was called.
nsIWebProgressListener
uriloader/base/nsiwebprogresslistener.idlscriptable this interface is implemented by clients wishing to listen in on the progress associated with the loading of asynchronous requests in the context of a nsiwebprogress instance as well as any child nsiwebprogress instances.
...esslistener", "nsisupportsweakreference"]), onstatechange: function(awebprogress, arequest, aflag, astatus) { let win = awebprogress.domwindow; let outerwindowid = win.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindowutils) .outerwindowid; sendasyncmessage("myaddonmessage", { name: "onstatechange", flag: aflag, status: astatus, }); }, onlocationchange: function(aprogress, arequest, auri, aflag) { let win = awebprogress.domwindow; let outerwindowid = win.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindowutils) ...
... .outerwindowid; sendasyncmessage("myaddonmessage", { name: "onlocationchange", outerwindowid: outerwindowid, uri: auri.spec, charset: auri.charset, flag: aflag, }); }, // for definitions of the remaining functions see related documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuschange: function(awebprogress, arequest, astatus, amessage) {}, onsecuritychange: function(awebprogress, arequest, astate) {} } let filter = cc["@mozilla.org/appshell/component/browser-status-filter;1"] .createinstance(ci.nsiwebprogress); filter.addprogresslistener(mylistener, ci.nsiwebprogress.notify_all); let webprogress = docshell...
nsIXmlRpcClient
ko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview void init(in string serverurl); void setauthentication(in string username, in string password); void clearauthentication(in string username, in string password); void setencoding(in string encoding); void setencoding(in unsigned long type, out nsiidref uuid, out nsqiresult result); void asynccall (in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, in nsisupports arguments, in pruint32 count); attributes attribute type description serverurl readonly nsiurl the url of the xml-rpc server inprogress readonly boolean whether or not a call is in progress fault readonly nsixmlrpcfault the most recent xml-rpc fault from returned from this server.
...the default charset if this function is not called is "utf-8" void setauthentication ( in string encoding ) ; parameters encoding encoding charset to be used asynccall() call remote method methodname asynchronously with given arguments.
...parameters listener a nsixmlrpcclientlistener that will get notified of xml-rpc events ctxt a context to be passed on to the listener methodname remote method to call arguments array of arguments to pass to the remote method count void asynccall ( in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, [array, size_is(count)] in nsisupports arguments, in pruint32 count ); createtype() convenience: return the correct nsisupportsprimitive for a given xml-rpc type, or nsisupportsarray or nsidictionary.
Mail composition back end
all of these methods are asynchronous operations.
...these are critical for message delivery since message sending is asynchronous.
...this method is performs the send operations asynchronously.
CacheStorage - Web APIs
async function getdata() { const cacheversion = 1; const cachename = `myapp-${ cacheversion }`; const url = 'https://jsonplaceholder.typicode.com/todos/1'; let cacheddata = await getcacheddata( cachename, url ); if ( cacheddata ) { console.log( 'retrieved cached data' ); return cacheddata; } console.log( 'fetching fresh data' ); const cachestorage ...
...async function getcacheddata( cachename, url ) { const cachestorage = await caches.open( cachename ); const cachedresponse = await cachestorage.match( url ); if ( !
...async function deleteoldcaches( currentcache ) { const keys = await caches.keys(); for ( const key of keys ) { const isourcache = 'myapp-' === key.substr( 0, 6 ); if ( currentcache === key || !
Clipboard - Web APIs
WebAPIClipboard
all of the clipboard api methods operate asynchronously; they return a promise which is resolved once the clipboard access has been completed.
...this asynchronous operation signals that it's finished by resolving the returned promise.
... clipboard availability the asynchronous clipboard api is a relatively recent addition, and the process of implementing it in browsers is not yet complete.
Using files from web applications - Web APIs
next, we establish the filereader to handle asynchronously loading the image and attaching it to the img element.
...this can be done asynchronously very easily.
... asynchronously handling the file upload process this example, which uses php on the server side and javascript on the client side, demonstrates asynchronous uploading of a file.
HTMLImageElement.complete - Web APIs
it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running.
...these photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background.
... let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ...
History - Web APIs
WebAPIHistory
back() this asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's back button.
... forward() this asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's forward button; this is equivalent to history.go(1).
... go() asynchronously loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1 for the next page.
RTCPeerConnection.setLocalDescription() - Web APIs
the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously.
... pc.addeventlistener("negotiationneeded", async (event) => { await pc.setlocaldescription(); signalremotepeer({ description: pc.localdescription }); }); other than error handling, that's about it!
... async function handlenegotiationneededevent() { try { await offer = pc.createoffer(); pc.setlocaldescription(offer); signalremotepeer({ description: pc.localdescription }); } catch(err) { reporterror(err); } } this begins by creating an offer by calling createoffer(); when that succeeds, we call setlocaldescription().
WritableStream.WritableStream() - Web APIs
if this process is to be done asynchronously, it can return a promise to signal success or failure.
...if this process is asynchronous, it can return a promise to signal success or failure.
...if this process is asynchronous, it can return a promise to signal success or failure.
HTML in XMLHttpRequest - Web APIs
var xhr = new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature.
...first, the detection result is obtained asynchronously, because html support is only available in the asynchronous mode.
...onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); } } try { xhr.open("get", "detect.html"); xhr.responsetype = "document"; xhr.send(); } catch (e) { window.settimeout(function() { if (!done) { done = true; callback(false); } }, 0); } } the argument callback is a function that will be called asynchronously with true as the only argument if html parsing is supported and false as the only argument if html parsing is not supported.
JavaScript reference - JavaScript
ndexed collections array int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array keyed collections map set weakmap weakset structured data arraybuffer sharedarraybuffer atomics dataview json control abstraction promise generator generatorfunction asyncfunction reflection reflect proxy internationalization intl intl.collator intl.datetimeformat intl.displaynames intl.listformat intl.locale intl.numberformat intl.pluralrules intl.relativetimeformat webassembly webassembly webassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly...
....linkerror webassembly.runtimeerror statements javascript statements and declarations control flowblock break continue empty if...else switch throw try...catch declarations var let const functions and classes function function* async function return class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with expressions and operators javascript expressions and operators.
... primary expressionsthis function class function* yield yield* async function await [] {} /ab+c/i ( ) null left-hand-side expressions property accessors new new.target super ...obj increment & decrement a++ a-- ++a --a unary operators delete void typeof + - ~ !
Populating the page: how browsers work - Web Performance
parsing can continue when a css file is encountered, but <script> tags—particularly those without an async or defer attribute—block rendering, and pause the parsing of html.
... <link rel="stylesheet" src="styles.css"/> <script src="myscript.js" async></script> <img src="myimage.jpg" alt="image description"/> <script src="anotherscript.js" async></script> in this example, while the main thread is parsing the html and css, the preload scanner will find the scripts and image, and start downloading them as well.
... to ensure the script doesn't block the process, add the async attribute, or the defer attribute if javascript parsing and execution order is not important.
content/worker - Archive of obsolete content
methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded.
...calling the self.postmessage() function from a content script will asynchronously emit the message event on the corresponding worker.
Adding menus and submenus - Archive of obsolete content
it's best to show an item with a throbber image (see chrome://global/skin/icons/loading_16.png) so the user knows there's something going on, and asynchronously fill its contents.
... we'll look into some asynchronous techniques further ahead in the tutorial.
Appendix D: Loading Scripts - Archive of obsolete content
advantages asynchronous: workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread.
... safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous execution.
Helper Apps (and a bit of Save As) - Archive of obsolete content
calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog.
... ongoing work support synchronous dialogs, not just asynchronous ones (fixes many issues related to pre-downloading, content-decoding, etc).
Mozilla Application Framework in Detail - Archive of obsolete content
necko features include support for asynchronous i/o, a generic disk and memory cache service, asynchronous caching dns resolution, web proxies, and https.
...mozilla's xml-rpc support includes synchronous and asynchronous requesting and downloading of data from a server.
XML in Mozilla - Archive of obsolete content
scheme obsolete since gecko 1.9.1 w3c recommendation xpointer xmlns() scheme obsolete since gecko 1.9.1 w3c recommendation xpointer fixptr() scheme obsolete since gecko 1.9.1 this scheme is simply a wrapper for fixptr xpointer xpath1() scheme obsolete since gecko 1.9.1 internet-draft document.load(), document.async part of dom level 3 load & save module, a w3c working draft xhtml we have reasonable xhtml support, most things should work.
...mozilla currently implements only the load() method and the document.async property.
Using IO Timeout And Interrupt On NT - Archive of obsolete content
on windows nt, nspr io is implemented using nt's overlapped (also called asynchronous) io.
...the win95 version runs without trouble on nt, but you would lose the better performance provided by nt fibers and asynchronous io.
Archived JavaScript Reference - Archive of obsolete content
do not use it!array.observe()the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
...such as firefox.number.tointeger()the number.tointeger() method used to evaluate the passed value and convert it to an integer, but its implementation has been removed.object.getnotifier()the object.getnotifer() method was used to create an object that allows to synthetically trigger a change, but has been deprecated and removed in browsers.object.observe()the object.observe() method was used for asynchronously observing the changes to an object.
Index - Game development
25 async scripts for asm.js games, javascript, asm.js, async every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process.
... in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28).
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
...ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading).
Client-side storage - Learn web development
you don't want to hang the browser while you wait for the results, so database operations are asynchronous, meaning that instead of happening immediately, they will happen at some point in the future, and you get notified when they're done.
... we have a problem here though — these two requests are both asynchronous, but we only want to try to display or store the video when both promises have fulfilled.
Multimedia: Images - Learn web development
optimizing image delivery despite being the largest consumer of bandwidth, images load asynchronously so the visitor can see the page as they download and therefore, their impact on perceived performance is far lower than many expect.
... rendering strategy as images are loaded asynchronously and continue to load after the first paint, if their dimensions aren't defined before load, they can cause reflows to the page content.
Web performance resources - Learn web development
to load css asynchronously one can simpy set the media type to print and then change to all once loaded.
... <style type="text/css"> // insert your css here </style> javascript avoid javascript blocking by using the async or defer attributes, or link javascript assets after the page's dom elements.
Benchmarking
async stacks async stacks no longer impact performance since firefox 78, as bug 1601179 limits async stack capturing to when devtools is opened.
... another option that is on by default in non-release builds is the preference javascript.options.asyncstack, which provides better debugging information to developers.
Browser chrome tests
asynchronous tests when writing async tests, you can use the add_task method with promises.
... the test suite also supports asynchronous tests, using the same function names as mochitest.
Process scripts
ables the process script to receive messages from the chrome side, and to send messages to the chrome side: // process-script.js if (services.appinfo.processtype == services.appinfo.process_type_content) { dump("welcome to the process script in a content process"); } else { dump("welcome to the process script in the main process"); } // message is sent using contentprocessmessagemanager sendasyncmessage("hello"); in this example, the dump() statement will run once in each content process as well as in the main process.
...if you do, you must call removedelayedprocessscript() when your extension is disabled or removed the message-passing apis are the same: sendasyncmessage() is available in both directions, while sendsyncmessage() is available from content to chrome only process scripts are system-privileged, and have access to the components object.
mozbrowserscrollviewchange
the mozbrowserscrollviewchange event is fired when asynchronous scrolling (i.e.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollviewchange", function( event ) { console.log("scrolling has " + event.details.state + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
Browser API
mozbrowserasyncscroll sent when the browser <iframe> content scrolls (the apcz version.) see also mozbrowserscroll.
...this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange sent when asynchronous scrolling (i.e.
HTML parser threading
(only the already executed ops are destructed and the rest are left in the queue.) the last op in the queue may be an op for attempting to execute a script that may block the parser (ops for attempting to execute async and defer scripts are normal tree ops and don't need to be the last op in a queue).
...preparing the parser thread for script execution when the parser thread sees that it has generated a tree op that attempts to execute a (non-async, non-defer) script, it starts speculating.
IME handling guide
however, in a remote process in e10s mode, this case never occurs since requests to native ime is handled asynchronously.
... then, imecontentobserver will notify some changes caused by the dispatched widgetcompositionevents (they are notified synchronously in chrome or non-e10s mode, but asynchronously from a remote process in e10s mode).
IPDL Best Practices
consider the following protocol: async protocol pasyncquerier { child: pasyncquery(); } async protocol pasyncquery { child: kickoffquery(nsstring query); parent: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent.
... it makes sense to fold construction and the first message together, as well as the penultimate and deletion messages, so that the final protocol looks like this: async protocol pasyncquerier { child: pasyncquery(nsstring query); } async protocol pasyncquery { parent: __delete__(nsstring result); } ...
Implementing Download Resuming
(it is possible to pass an empty string as the id; however, this means that you have no assurance that the file remained unchanged) now, you can open the channel as usual (using nsichannel.asyncopen() in the common case) and write to the file in the ondataavailable notifications.
... you may want to use nsisimplestreamlistener to simplify this task; to get progress notifications, you can implement nsiprogresseventsink and set an interface requester as the notificationcallbacks of the channel that gives out such an event sink (this needs to be done before calling asyncopen).
Introduction to Layout in Mozilla
(tables, blocks, xul boxes) reflow “global” reflows initial, resize, style-change processed immediately via presshell method incremental reflows targeted at a specific frame dirty, content-changed, style-changed, user-defined nshtmlreflowcommand object encapsulates info queued and processed asynchronously, nsipressshell::appendreflowcommand, processreflowcommands incremental reflow recursively descend to target recovering reflow state child rs.reason set to incremental incremental reflow process reflow “normally” at target frame child rs.reason set based on rc’s type incremental reflow propagate damage to frames later “in the flo...
...w” incremental reflow multiple reflow commands are batched nsreflowpath maintains a tree of target frames amortize state recovery and damage propagation cost painting as reflow proceeds through the frame hierarchy, areas are invalidated via nsiviewmanager::updateview unless immediate, invalid areas are coalesced and processed asynchronously via os expose event native expose event dispatched to widget; widget delegates to the view manager view manager paints views back-to-front, invoking presshell’s paint method presshell::paint walks from the view to the frame; invokes nsiframe::paint for each layer incrementalism single-threaded simple (no locking) can’t leave event queue unattended content construction unwinds “at will...
Add-on Manager
many functions in the add-on manager interface operate asynchronously returning results through callbacks passed to the functions.
...all of its functions are asynchronous, meaning that a callback function must be passed to receive the addon instances.
OSFile.jsm
calling os.file from the main thread asynchronous, off-main thread file i/o, main thread api.
... calling os.file.directoryiterator from the main thread asynchronous, off-main thread file directory access, main thread api.
JavaScript code modules
netutil.jsm provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously.
... task.jsm implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
Nonblocking IO In NSPR
the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_nonblocking, &optval, sizeof(optval)); programming constraints there are some constraints due to the use of nt asynchronous i/o in the nspr.
...there is a second constraint, due to the use of nt asynchronous i/o and the recycling of used sockets: the new socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> inherits the blocking/nonblocking io mode of the listening socket and this cannot be changed.
HTTP delegation
the api should allow nss to use the http client either asynchronously or synchronously.
...please read the source code documentation to learn how to use this api synchronously or asynchronously.
HTTP delegation
the api should allow nss to use the http client either asynchronously or synchronously.
...please read the source code documentation to learn how to use this api synchronously or asynchronously.
Shell global objects
callfunctionwithasyncstack(function, stack, asynccause) call function, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws.
...the specified asynccause is attached to the provided stack frame.
History Service Design
in future this will probably change in favour of storage asynchronous statements, so that the inserts will be queued-up by mozstorage itself in a separate thread.
... expiration expiration is an important part of data management for two reasons: privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal database maintenance: having cleaner and smaller tables helps queries performances expiration is done at certain moments, but in future will most likely be moved to async queries, to be executed on a separate thread.
HOWTO
async network requests problem you want to make network requests or do other asynchronous work in xpcshell.
...put the following at the end of your script: // do async processing // from <https://developer.mozilla.org/en/xpconnect/xpcshell/howto> print("doing async work"); gscriptdone = false; var gthreadmanager = cc["@mozilla.org/thread-manager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(true); while (mainthread.haspendingevents()) mainthread.processnextevent(true); 2.
Observer Notifications
http-on-opening-request similar to http-on-modify-request, but called earlier (synchronously during the channel's asyncopen() call), and some channel attributes (proxyinfo) may be missing.
... use only if your observer must be called before asyncopen returns.
mozIPlaceInfo
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides additional info for a places entry 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) attributes attribute type description frecency long read only: the frecency of the place.
... see also moziasynchistory mozivisitinfo ...
mozIStorageAggregateFunction
if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
...if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
mozIStorageBindingParamsArray
the mozistoragebindingparamsarray interface is a container for mozistoragebindingparams objects, and is used to store sets of bound parameters that will be used by the mozistoragestatement.executeasync().
...the appended parameters will be used when mozistoragestatement.executeasync() is called.
mozIStorageCompletionCallback
this interface should be implemented to handle callbacks from asynchronous storage api routines.
... last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports method overview void complete(); methods complete() called when an asynchronous storage routine has completed.
mozIStorageStatementCallback
the mozistoragestatementcallback interface represents a callback handler that the storage api calls with result, error, and completion notifications while handling asynchronous database queries.
...this function may be called more than once with a different storageierror each time for any given asynchronous statement, and handlecompletion will be called once the statement is complete.
mozIVisitInfo
toolkit/components/places/moziasynchistory.idlscriptable this interface provides additional info for a visit.
... see also moziasynchistory ...
mozIVisitStatusCallback
toolkit/components/places/moziasynchistory.idlscriptable this interface provides callback handling functionality for moziasynchistory.isurivisited 1.0 66 introduced gecko 11.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) method overview void isvisited(in nsiuri auri, in boolean avisitedstatus); methods isvisited() called when the moziasynchistory.isurivisited() method's check to determine whether a given uri has been visited has completed.
... see also moziasynchistory ...
nsIApplicationCacheChannel
exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel.
...exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel.
nsIAutoCompleteSearch
results can be sent to the listener either synchronously or asynchronously, depending on the implementation.
... method overview void startsearch(in astring searchstring, in astring searchparam, in nsiautocompleteresult previousresult, in nsiautocompleteobserver listener); void stopsearch(); methods startsearch() search for a given string and notify a listener (either synchronously or asynchronously) of the result.
nsIBrowserHistory
you should use moziasynchistory.updateplaces() instead.
... remarks visits are removed synchronously, but pages are expired asynchronously, off the main thread.
nsICacheEntryDescriptor
use the stream transport service to asynchronously read this stream on a background thread.
...use the stream transport service to asynchronously write to this stream on a background thread.
nsICachingChannel
load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a call to asyncopen.
...a stream listener can check isfromcache() to determine if the asyncopen will actually result in data being streamed.
nsIContentPrefService2
dom/interfaces/base/nsicontentprefservice2.idlscriptable asynchronous api for content preferences 1.0 66 introduced gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17) description content preferences allow the application to associate arbitrary data, or "preferences", with specific domains, or web "content".
...callbacks the methods of callback objects are always called asynchronously.
nsIDNSListener
inherits from: nsisupports last changed in gecko 1.7 method overview void onlookupcomplete(in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus); methods onlookupcomplete() called when an asynchronous host lookup completes.
... void onlookupcomplete( in nsicancelable arequest, in nsidnsrecord arecord, in nsresult astatus ); parameters arequest the value returned from asyncresolve.
nsIDNSRequest
inherits from: nsisupports last changed in gecko 1.7 method overview void cancel(); methods cancel() called to cancel a pending asynchronous dns request.
... the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort.
nsIJetpack
*/); void registerreceiver(in astring amessagename, in jsval areceiver); void unregisterreceiver(in astring amessagename, in jsval areceiver); void unregisterreceivers(in astring amessagename); void evalscript(in astring ascript); nsivariant createhandle(); void destroy(); methods sendmessage() this method asynchronously sends a message to the jetpack process.
... evalscript() this asynchronously sends code to the jetpack process for evaluation.
nsIMessageSender
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsimessagelistenermanager message senders enable clients to send asynchronous messages to a single "other side".
...methods void sendasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); sendasyncmessage() send messagename and obj to the "other side" of this message manager.
nsIMsgFilterCustomAction
e manual only) * @param filtertype type of filter being applied * @param msgwindow message window */ void apply(in nsiarray msghdrs /* nsimsgdbhdr array */, in autf8string actionvalue, in nsimsgcopyservicelistener copylistener, in nsmsgfiltertypetype filtertype, in nsimsgwindow msgwindow); /* does this action start an async action?
... */ readonly attribute boolean isasync; /// does this action need the message body?
nsINavHistoryQueryOptions
asyncenabled boolean when true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so.
... note: currently, only bookmark folder containers support being opened asynchronously.
nsIProcess2
to create an instance, use: var process2 = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2); method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); methods runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running.
... void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set.
nsIRequestObserver
inherits from: nsisupports last changed in gecko 1.0 method overview void onstartrequest(in nsirequest arequest, in nsisupports acontext); void onstoprequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode); methods onstartrequest() called to signify the beginning of an asynchronous request.
... onstoprequest() called to signify the end of an asynchronous request.
nsITextInputProcessorNotification
if the callback doesn't want to commit the composition synchronously, it's okay to commit it later (i.e., asynchronously).
... if the callback doesn't want to cancel the composition synchronously, it's okay to cancel it later (i.e., asynchronously).
nsITransport
in addition, in non-blocking mode, the stream is guaranteed to support nsiasyncinputstream.
...in addition, in non- blocking mode, the stream is guaranteed to support nsiasyncoutputstream.
XPCOM Interface Reference
iaccessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstallcallbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletioncallbackmozistorageconnectionmozistorageerrormozistoragefunctionmozistoragependingstatem...
...ntnsiaccessibletextnsiaccessibletextchangeeventnsiaccessibletreecachensiaccessiblevaluensiaccessiblewin32objectnsialertsservicensiannotationobservernsiannotationservicensiappshellnsiappshellservicensiappstartupnsiappstartup_mozilla_2_0nsiapplicationcachensiapplicationcachechannelnsiapplicationcachecontainernsiapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirectcallbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthpromptcallbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertlistener2n...
XPCOM Interface Reference by grouping
kreference nsivariant do not use nsienumerator nsiinprocesscontentframemessagemanager nsiscriptableio nsixpcscriptable future nsixmlhttprequestupload obsolete nsixmlrpcclient nsixmlrpcfault security auth nsiauthmodule nsiauthprompt nsiauthpromptprovider nsiauthpromptwrapper nsiasyncverifyredirectcallback content nsicontentpolicy credentials nsilogininfo nsiloginmanager using nsiloginmanager nsiloginmanagerstorage nsiloginmetainfo history nsiglobalhistory nsiglobalhistory2 nsiglobalhistory3 ssl nsibadcertlistener2 ...
... filesystem nsidirectoryenumerator nsidirectoryiterator nsidirectoryservice nsidirectoryserviceprovider nsidirectoryserviceprovider2 nsidirindex nsidirindexlistener nsidirindexparser nsifile nsilocalfile stream nsiasyncinputstream nsiasyncoutputstream nsiasyncstreamcopier nsibinaryinputstream nsibinaryoutputstream nsicontentsniffer nsiconverterinputstream nsifileinputstream nsifileoutputstream nsiinputstream nsiinputstreamcallback nsioutputstream nsioutputstreamcallback ...
Performance
the asynchronous writes discussed below removes most of the immediate penalty of a commit, so you will not notice the problem as much.
...this made shutdown very slow because the asyncio thread would block shutdown (bug 328598).
Mail and RDF
asynchronously notifying rdf when the data itself changes, rdf needs to be notified.
...df.getresource("http://home.netscape.com/nc-rdf#totalmessages"); function gettarget(target, property, unused) { var folder = target.queryinterface(components.interfaces.nsimsgfolder); if (property == msgcountarc) { var msgcount = folder.gettotalmessages(false); var result = rdf.getliteral(msgcount.tostring()); return result; } } asynchronously notifying rdf when a mail object's data changes and the data is reflected in rdf by notifying all of the observers that rdf has registered with the datasource.
Debugger.Object - Firefox Developer Tools
(this is always equal to obj.script.isgeneratorfunction, assuming obj.script is a debugger.script.) isasyncfunction if the referent is a debuggee function, returns true if the referent is an async function, defined with an async function expression or statement, or false if it is some other sort of function.
...(this is always equal to obj.script.isasyncfunction, assuming obj.script is a debugger.script.) ispromise true if the referent is a promise; false otherwise.
Beacon API - Web APIs
the beacon interface is used to schedule an asynchronous and non-blocking request to a web server.
... user agents will typically ignore asynchronous xmlhttprequests made in an unload handler.
ClipboardItem - Web APIs
async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're ...
... async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification.
Clipboard API - Web APIs
the clipboard api provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard.
...the specification refers to this as the 'async clipboard api.' clipboardevent secure context represents events providing information related to modification of the clipboard, that is cut, copy, and paste events.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to register it with the content index.
... // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope.
ContentIndex.delete() - Web APIs
examples below is an asynchronous function, that removes an item from the content index.
... async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete method can also be used within the service worker scope.
ContentIndex.getAll() - Web APIs
examples the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li...
Element - Web APIs
WebAPIElement
element.requestfullscreen() asynchronously asks the browser to make the element full-screen.
... element.requestpointerlock() allows to asynchronously ask for the pointer to be locked on the given element.
FetchEvent - Web APIs
if it finds a match in the cache, it asynchronously updates the cache for next time.
... event.respondwith(async function() { // try to get the response from a cache.
Fetch basic concepts - Web APIs
in a nutshell at the heart of fetch are the interface abstractions of http requests, responses, headers, and body payloads, along with a global fetch method for initiating asynchronous resource requests.
... fetch takes the asynchronous nature of such requests one step further.
HTMLImageElement.decoding - Web APIs
async: decode the image asynchronously to reduce delay in presenting other content.
...if doing so would cause problems, you can specify sync to disable asynchronous loading.
Basic concepts - Web APIs
indexeddb is an asynchronous api that can be used in most contexts, including web workers.
... the indexeddb api is mostly asynchronous.
Intersection Observer API - Web APIs
the intersection observer api provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
...each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level document's viewport.
NavigationPreloadManager - Web APIs
examples feature detecting and enabling navigation preloading addeventlistener('activate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads!
... addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network.
PaymentRequest.canMakePayment() - Web APIs
parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards.
... async function initpaymentrquest() { const details = { total: { label: "total", amount: { currency: "usd", value: "0.00", }, }, }; const supportsapplepay = new paymentrequest( [{ supportedmethods: "https://apple.com/apple-pay" }], details ).canmakepayment(); // supports apple pay?
PaymentRequest: merchantvalidation event - Web APIs
request.addeventlistener("merchantvalidation", event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation a...
... you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentRequest.shippingOption - Web APIs
this demotrates synchrounous and asynchronous updates to a payment sheet.
... const request = new paymentrequest(methoddata, details, options); // async update to details request.onshippingaddresschange = ev => { ev.updatewith(checkshipping(request)); }; // sync update to the total request.onshippingoptionchange = ev => { const shippingoption = shippingoptions.find( option => option.id === request.id ); const newtotal = { currency: "usd", label: "total due", value: calculatenewtotal(shippingoption), }; ev.updatewith({ ...details, total: newtotal }); }; async function checkshipping(request) { try { const json = request.shippingaddress.tojson(); await ensurecanshipto(json); const { shippingoptions, total } = await calculateshipping(json); return { ...details, shippingoptions, total }; } catch (err) { return { ...deta...
PaymentResponse: payerdetailchange event - Web APIs
response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
...data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addeventlistener equivalent you could also set up the event handler using the addeventlistener() method: response.addeventlistener("payerdetailchange", async ev => { ...
RTCPeerConnection.addTrack() - Web APIs
here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations.
... for example, consider this function that an application might use to begin streaming a device's camera and microphone input over an rtcpeerconnection to a remote peer: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoelem.srcobject = stream; this sets the video element's cur...
RTCPeerConnection.peerIdentity - Web APIs
example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller.
...*/ async function getidentityassertion(pc) { try { const identity = await pc.peeridentity; return identity; } catch(err) { console.log("error identifying remote peer: ", err); return null; } } specifications specification status comment identity for webrtc candidate recommendation initial specification.
RTCPeerConnection.setRemoteDescription() - Web APIs
the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously.
...this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
let startreport; async function networkteststart(pc) { if (pc) { startreport = await pc.getstats(); } } given an rtcpeerconnection, pc, this calls its getstats() method to obtain a statistics report object, which it stores in startreport for use once the end-of-test data has been collected by networkteststop().
... async function networkteststop(pc) { if (pc) { let statsbox = document.queryselector(".stats-box"); let endreport = await pc.getstats(); for (let endremoteoutbound of endreport.values()) { if (endremoteoutbound.type === "remote-outbound-rtp") { let startremoteoutbound = startreport.get(endremoteoutbound.id); if (startremoteoutbound) { let startinboundstat...
ReadableStream.ReadableStream() - Web APIs
if this process is to be done asynchronously, it can return a promise to signal success or failure.
...if this process is asynchronous, it can return a promise to signal success or failure.
ReadableStream - Web APIs
readablestream.getiterator() creates a readablestream async iterator instance and locks the stream to it.
... readablestream[@@asynciterator]() alias of getiterator method.
Using the Screen Capture API - Web APIs
starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise dire...
... async function startcapture() { logelem.innerhtml = ""; try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); dumpoptionsinfo(); } catch(err) { console.error("error: " + err); } } after clearing the contents of the log in order to get rid of any leftover text from the previous attempt to connect, startcapture() calls getdisplaymedia(), pass...
Screen Wake Lock API - Web APIs
the wakelock.request method is promise based and so we can create an asynchronous function, which in turn updates the ui to reflect the wake lock is active.
... // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake lock active statuselem.textcontent = 'wake lock is active!'; } catch (err) { // if wake lock request fails - usually system related, such as battery statuselem.textcontent = `${err.name}, ${err.message}`; } } releasing wake lock the following example shows how to release the previously acquired wake lock.
SourceBuffer - Web APIs
sourcebuffer.appendbufferasync() starts the process of asynchronously appending the specified buffer to the sourcebuffer.
... sourcebuffer.removeasync() starts the process of asynchronously removing media segments in the specified range from the sourcebuffer.
SubtleCrypto.deriveBits() - Web APIs
async function derivesharedsecret(privatekey, publickey) { const sharedsecret = await window.crypto.subtle.derivebits( { name: "ecdh", namedcurve: "p-384", public: publickey }, privatekey, 128 ); const buffer = new uint8array(sharedsecret, 0, 5); const sharedsecretvalue = document.queryselector(".ecdh .derived-bits-value"); sharedsecretvalue.classlist.add("f...
...*/ async function getderivedbits() { const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const derivedbits = await window.crypto.subtle.derivebits( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, 256 ); const buffer = new uint8array(derivedbits, 0, 5); const derive...
SubtleCrypto.deriveKey() - Web APIs
/* derive an aes key, given: - our ecdh private key - their ecdh public key */ function derivesecretkey(privatekey, publickey) { return window.crypto.subtle.derivekey( { name: "ecdh", public: publickey }, privatekey, { name: "aes-gcm", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreesharedsecretkey() { // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange public keys securely let aliceskeypair = await window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivekey"] ); let bobskeypair = await window.c...
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), "pbkdf2", false, ["derivebits", "derivekey"] ); } async function encrypt(plaintext, salt, iv) { let keymaterial = await getkeymaterial(); let key = await window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256}, true, [ "encrypt", "decrypt" ] ); return window.crypto.subtle.encrypt( { name...
SubtleCrypto.digest() - Web APIs
the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are ...
...the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const msguint8 = new textencoder().encode(message); // encode as (utf-8) uint8array const hashbuffer = await crypto.subtle.digest('sha-256', msguint8); // hash the message const hasharray = array.from(new uint8array(hashbuffer)); // convert buffer to byte array const hashhex = hasharray.map(b => b.tostring(16).padstart(2, '0')).join(''); // convert bytes to hex string return hashhex; } const digesthex = await digestmessage(text); console.log(digesthex); specifi...
WakeLock.request() - Web APIs
WebAPIWakeLockrequest
examples the following asynchronous function requests a wakelocksentinel object.
... const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'request()' in that specification.
WakeLock - Web APIs
WebAPIWakeLock
examples the following asynchronous function requests a wakelocksentinel object.
... const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'wakelock' in that specification.
WakeLockSentinel.type - Web APIs
examples this example shows an asynchronous function that acquires a wakelocksentinel, then logs the type to the console.
... const requestwakelock = async () => { wakelock = await navigator.wakelock.request('screen'); console.log(wakelock.type); // logs 'screen' }; requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'wakelocktype' in that specification.
WakeLockSentinel - Web APIs
examples in this example we create an asynchronous function which requests a wakelocksentinel.
... // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // listen for our release event wakelock.addeventlistener('release', () => { // if wake lock is released alter the ui accordingly }); } catch (err) { // if wake lock request fails - usually system related, such as battery } } wakelockonbutton.addeventlistener('click', () => { requestwakelock(); }) wakelockoffbutton.addeventlistener('click', () => { if (wakelock !== null) { ...
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.beginquery() begins an asynchronous query.
... webgl2renderingcontext.endquery() marks the end of an asynchronous query.
WebGLRenderingContext.makeXRCompatible() - Web APIs
*/ outputcanvas.addeventlistener("webglcontextrestored", (event) => { loadsceneresources(currentscene); }); async function onstartedxrsession(xrsession) { try { await gl.makexrcompatible(); } catch(err) { switch(err) { case aborterror: showsimplemessagebox("unable to transfer the game to your xr headset.", "cancel"); break; case invalidstateerror: showsimplemessagebox("you don't appear to have a compatible xr headset available.", "cancel"); break; ...
... default: handlefatalerror(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr = true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { currentscene = "scene1"; loadsceneresources(currentscene); /* and so on */ } this works by having two buttons, one which starts the game normally and the other which starts the game in vr mode.
Advanced techniques: Creating and sequencing audio - Web APIs
loading the sample we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has ...
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to take an array of files and loop over them to load more than one sample.
Migrating from webkitAudioContext - Web APIs
because of these problems, this version of the createbuffer() method has been removed, and you should use the asynchronous decodeaudiodata() method instead.
...st(); xhr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful.
Functions and classes available to Web Workers - Web APIs
across the network.) 39 (39) (mostly in 34 (34) behind pref, although a few features are later.) no support 42 41 behind pref 10.1 filereader this api allows asynchronous read of blob and file objects.
... (yes) (yes) (yes) (yes) promise javascript objects that allow you to write asynchronous functions.
XMLHttpRequest.open() - Web APIs
syntax xmlhttprequest.open(method, url[, async[, user[, password]]]) parameters method the http request method to use, such as "get", "post", "put", "delete", etc.
... async optional an optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously.
Event reference
mozbrowseractivitydone firefox os browser api-specific sent when some activity has been completed (complete description tbd.) mozbrowserasyncscroll firefox os browser api-specific sent when the scroll position within a browser <iframe> changes.
...this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange firefox os browser api-specific sent when asynchronous scrolling (i.e.
Ajax - Developer guides
WebGuideAJAX
asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together, including html or xhtml, css, javascript, dom, xml, xslt, and most importantly the xmlhttprequest object.
... filereader api the filereader api lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using file or blob objects to specify the file or data to read.
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
in html5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set.
... some contexts from which you should not call document.write() include: scripts created using document.createelement() event handlers settimeout() setinterval() <script async src="..."> <script defer src="..."> if you use the same mechanism for loading script libraries for all browsers including ie, then your code probably will not be affected by this change.
Index - Developer guides
WebGuideIndex
2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here.
... 17 event developer guide dom, event, guide, needsupdate, events events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.
Private class fields - JavaScript
private static methods may be generator, async, and async generator functions.
... class classwithprivatemethod { #privatemethod() { return 'hello world' } getprivatemessage() { return this.#privatemethod() } } const instance = new classwithprivatemethod() console.log(instance.getprivatemessage()) // expected output: "hello worl​d" private instance methods may be generator, async, or async generator functions.
Public class fields - JavaScript
you may make use of generator, async, and async generator functions.
... class classwithfancymethods { *generatormethod() { } async asyncmethod() { } async *asyncgeneratormethod() { } } inside instance methods, this refers to the instance itself.
Deprecated and obsolete features - JavaScript
object.observe() asynchronously observing the changes to an object.
... array property description array.observe() asynchronously observing changes to arrays.
Array.prototype.forEach() - JavaScript
kindly make sure you are aware of the implications while using promises(or async functions) as foreach callback.
... example code let ratings = [5, 4, 5]; let sum = 0; let sumfunction = async function (a, b) { return a + b } ratings.foreach(async function(rating) { sum = await sumfunction(sum, rating) }) console.log(sum) // naively expected output: 14 // actual output: 0 examples no operation for uninitialized values (sparse arrays) const arraysparse = [1,3,,7] let numcallbackruns = 0 arraysparse.foreach((element) => { console.log(element) numcallbackruns++ }) console.log("numcallbackruns: ", numcallbackruns) // 1 // 3 // 7 // numcallbackruns: 3 // comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
Function.caller - JavaScript
it returns null for strict, async function and generator function callers.
...it's also null for strict, async function and generator function callers.
Promise.allSettled() - JavaScript
it is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.
... return value a pending promise that will be asynchronously fulfilled once every promise in the specified collection of promises has completed, either by successfully being fulfilled or by being rejected.
Promise.race() - JavaScript
return value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject.
... examples asynchronicity of promise.race this following example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); //...
WebAssembly.Instance() constructor - JavaScript
syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times.
...e: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); specifications specification webassembly javascript interfacethe defi...
WebAssembly.Module() constructor - JavaScript
however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile().
... syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times.
Standard built-in objects - JavaScript
arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).
... promise generator generatorfunction asyncfunction reflection reflect proxy internationalization additions to the ecmascript core for language-sensitive functionalities.
Expressions and operators - JavaScript
async function the async function defines an async function expression.
... await pause and resume an async function and wait for the promise's resolution/rejection.
function* - JavaScript
generators in javascript -- especially when combined with promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as callback hell and inversion of control.
... however, an even simpler solution to these problems can be achieved with async functions.
import - JavaScript
import '/modules/my-module.js'; this works with dynamic imports as well: (async () => { if (somethingistrue) { // import module for side effects await import('/modules/my-module.js'); } })(); if your project uses packages that export esm, you can also import them for side effects only.
... (async () => { if (somethingistrue) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time.
Statements and declarations - JavaScript
async function declares an async function with the specified parameters.
... for await...of iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property.
Compiling an Existing C Module to WebAssembly - WebAssembly
now you only need some html and javascript to load your new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> and you will see the correct version number in the output: note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc.
...luckily, the canvas api has canvasrenderingcontext2d.getimagedata — that gives you an uint8clampedarray containing the image data in rgba: async function loadimage(src) { // load image const imgblob = await fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); retur...
Communicating using "port" - Archive of obsolete content
to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing.
Content Scripts - Archive of obsolete content
to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() messages are asynchronous: that is, the sender does not wait for a reply from the recipient but just emits the message and continues processing.
passwords - Archive of obsolete content
web server at http://www.example.com requested authentication with a response code like this: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" realm: "exampleco login" oncomplete and onerror this api is explicitly asynchronous, so all its functions take two callback functions as additional options: oncomplete and onerror.
content/symbiont - Archive of obsolete content
usage a symbiont loads the specified contenturl and content scripts into a frame, and sets up an asynchronous channel between the content scripts and the add-on code, enabling them to exchange messages using the port or postmessage apis.
io/text-streams - Archive of obsolete content
writeasync(str, callback) writes a string on a background thread.
places/bookmarks - Archive of obsolete content
save() and search() are both asynchronous functions: they synchronously return a placesemitter object, which then asynchronously emits events as the operation progresses and completes.
places/favicon - Archive of obsolete content
the platform service (moziasyncfavicons) retrieves favicon data stored from previously visited sites, and as such, will only return favicon urls for visited sites.
places/history - Archive of obsolete content
usage this module exports a single function, search(), which synchronously returns a placesemitter object which then asynchronously emits data and end or error events that contain information about the state of the operation.
remote/parent - Archive of obsolete content
the module loads asynchronously but you can start sending messages to the module immediately.
test/httpd - Archive of obsolete content
usage the most basic usage is: var { startserverasync } = require("sdk/test/httpd"); var srv = startserverasync(port, basepath); require("sdk/system/unload").when(function cleanup() { srv.stop(function() { // you should continue execution from this point.
ui/frame - Archive of obsolete content
since the event is dispatched asynchronously, the document may already be loaded by the time the event is received.
Low-Level APIs - Archive of obsolete content
core/promise implementation of promises to make asynchronous programming easier.
Open a Web Page - Archive of obsolete content
to open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); this function is asynchronous, so you don't immediately get back a tab object which you can examine.
JavaScript Debugger Service - Archive of obsolete content
var jsd = components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getservice(components.interfaces.jsdidebuggerservice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism.
Miscellaneous - Archive of obsolete content
e application running us services.appinfo.name; // returns "firefox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see around here: http://mxr.mozilla.org/mozilla1.8/so...pdates.js#1631 bug 338039 tracks improving this situatio...
How to convert an overlay extension to restartless - Archive of obsolete content
n the global for a window, but in jsm you'll need to fetch it from an interface: const xmlhttprequest = components.constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsixmlhttprequest"); here's how to load a file using it: function loadfile(url,type,returnresult) { var request = new xmlhttprequest(); request.open("get", url, true); // async=true request.responsetype = type; request.onerror = function(event) { logerrormessage("error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) returnresult(request.response); else request.onerror(event); }; request.send(); } loadfile("chrome://myaddon/content...
Jetpack Processes - Archive of obsolete content
privileged apis when script is evaluated in a jetpack process via a call to nsijetpack.evalscript(), the script's global scope is endowed with the following privileged apis: sendmessage(amessagename [, v1 [, v2 [, ...]]]) similar to nsijetpack.sendmessage(), this function asynchronously sends a message to the chrome process.
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
except for asynchronous processes, all processing stops while the dialog is up, so this technique is useful when you want to pin down a value that can vary during a process.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
nevertheless, the rise of web services like google maps, which used javascript and asynchronous communications, created an awareness of a set of technologies nicknamed ajax (asynchronous javascript and xml); that plus the advent of a number of libraries that paper over implementation differences between different web browsers has more recently led to a re-evaluation of javascript as a programming language.
Custom XUL Elements with XBL - Archive of obsolete content
this is likely due to some asynchronous operation related to node insertion.
Local Storage - Archive of obsolete content
if you need a complex database this can be heavy in terms of time and code, but this will only happen once and this can be done in a lazy or asynchronous way.
Creating a dynamic status bar extension - Archive of obsolete content
the true boolean value in the third parameter indicates that we want to process the request asynchronously.
Index of archived content - Archive of obsolete content
y npn_getvalue npn_getvalueforurl npn_hasmethod npn_hasproperty npn_identifierisstring npn_intfromidentifier npn_invalidaterect npn_invalidateregion npn_invoke npn_invokedefault npn_memalloc npn_memflush npn_memfree npn_pluginthreadasynccall npn_posturl npn_posturlnotify npn_releaseobject npn_releasevariantvalue npn_reloadplugins npn_removeproperty npn_requestread npn_retainobject npn_setexception npn_setproperty npn_setvalue npn_setvalueforurl npn_status npn_utf8f...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
3,163" href="#stream-converter"> <area alt="(11)" coords="485,133,537,163" href="#contenthandler"> <area alt="(9)" coords="445,132,484,165" href="#nsdocumentopeninfo::dispatchcontent"> <area alt="(8)" coords="405,133,439,162" href="#onstartrequest-innards"> <area alt="(7) onstartrequest()" coords="639,129,703,129,703,165,833,165,833,204,639,204" href="#onstartrequest" shape="poly"> <area alt="(6) asyncopen()" coords="637,121,709,121,709,96,783,96,783,58,637,58" href="#asyncopen" shape="poly"> <area alt="(5) open()" coords="311,306,432,371" href="#open"> <area alt="(4)" coords="90,384,127,417" href="#openuri-innards"> <area alt="(0) registercontentlistener()" coords="37,474,346,474,346,505,88,505,88,535,37,535" href="#registercontentlistener" shape="poly"> <area alt="(3) openuri() (nsuriloader)"...
Me - Archive of obsolete content
ArchiveMozillaJetpackMetaMe
onfirstrun() may be called anywhere in your jetpack, but if it is called as the result of some asynchronous operation such as a timeout or xmlhttprequest, it is ignored.
Tuning Pageload - Archive of obsolete content
since layout and painting happen asynchronously, while the parser is working there is no layout or painting.
visuallyselected - Archive of obsolete content
the visuallyselected attribute is set asynchronously, once the browser has switched to the selected tab.
Using the Editor from XUL - Archive of obsolete content
we get the url to load from the args element, then kick off the load: var url = document.getelementbyid("args").getattribute("value"); editorshell.loadurl(url); loading the document in the <iframe> of course happens asynchronously, so we need to know when we have a document that we can start editing.
2006-10-27 - Archive of obsolete content
he recommends that a non-xpcshell environment is needed really badly, but the big issue is that the xpcshell doesn't have an event loop, so nothing asynchronous can be tested.
2006-11-10 - Archive of obsolete content
discussions developing an extension like xmlhttprequest / nsidocument / mozilla_internal_api a discussion on how to develop an extension similar to xmlhttprequest but for a different protocol than http, emulating the asynchronous aspect.
2006-12-01 - Archive of obsolete content
discussions cancellable async requests discussions about a bug of calicalendar's async methods.
Browser-side plug-in API - Archive of obsolete content
npn_destroystream npn_forceredraw npn_getauthenticationinfo npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_invalidaterect npn_invalidateregion npn_memalloc npn_memflush npn_memfree npn_newstream npn_pluginthreadasynccall npn_poppopupsenabledstate npn_posturl npn_posturlnotify npn_pushpopupsenabledstate npn_reloadplugins npn_requestread npn_setvalue npn_setvalueforurl npn_status npn_useragent npn_version npn_write ...
NPN_GetURL - Archive of obsolete content
it is typically asynchronous but this is not guaranteed.
NPN_GetURLNotify - Archive of obsolete content
npn_geturlnotify() typically handles the url request asynchronously.
NPN_InvalidateRect - Archive of obsolete content
after calling this method, the plug-in receives a paint message asynchronously.
NPN_PostURL - Archive of obsolete content
npn_posturl is typically asynchronous: it returns immediately and only later handles the request.
NPN_PostURLNotify - Archive of obsolete content
npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify.
NPAPI plugin reference - Archive of obsolete content
npn_pluginthreadasynccall thread safe way to request that the browser calls a plug-in function on the browser or plugin thread (the thread on which the plug-in was initiated).
SAX - Archive of obsolete content
refixmapping: function(prefix) { // don't care }, // nsisupports queryinterface: function(iid) { if(!iid.equals(components.interfaces.nsisupports) && !iid.equals(components.interfaces.nsisaxcontenthandler)) throw components.results.ns_error_no_interface; return this; } }; start parsing the xml reader component can parse xml from a string, an nsiinputstream, or asynchronously via the nsistreamlistener interface.
Using JavaScript Generators in Firefox - Archive of obsolete content
generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later.
Array.observe() - Archive of obsolete content
the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
ecmascript 2016 array.prototype.includes() (firefox 43) typedarray.prototype.includes() (firefox 43) exponentiation operator (firefox 52) ecmascript 2017 object.values() (firefox 47) object.entries() (firefox 47) string.prototype.padstart() (firefox 48) string.prototype.padend() (firefox 48) object.getownpropertydescriptors() (firefox 50) async functions async function (firefox 52) async function expression (firefox 52) asyncfunction (firefox 52) await (firefox 52) trailing commas in function parameter lists (firefox 52) ecmascript 2018 spread in object literals and rest parameters (firefox 55) for await...of (firefox 57) global_objects/sharedarraybuffer (firefox 57, with flags) global_objects/promise/finall...
Object.observe() - Archive of obsolete content
the object.observe() method was used for asynchronously observing the changes to an object.
Archived open Web documentation - Archive of obsolete content
styling the amazing netscape fish cam page using javascript generators in firefox generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later.
Anatomy of a video game - Game development
long calculations can be performed on a web worker or a gpu at the same time as the browser uses its main thread to manage garbage collection, its other tasks, or handle asynchronous events.
Techniques for game development - Game development
using async scripts for asm.js especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's javascript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users.
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks.
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
parsing can continue when a css file is encountered, but <script> tags—particularly those without an async or defer attribute—blocks rendering, and pauses parsing of html.
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
there are front end optimization techniques that can improve perceived performance, such as adding the defer or async attribute to scripts, or placing scripts at the end of documents, and placing css in the head of documents.
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
when the called function finishes its work asynchronously, a function on the promise object called a resolution (or fulfillment, or completion) handler is called to let the original caller know that the task is complete.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
learn more technical reference asynchronous synchronous and asynchronous requests using the xmlhttprequest() api ...
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
asynchronous communications technical information the xmlhttprequest object.
beacon - MDN Web Docs Glossary: Definitions of Web-related terms
there is a w3c draft beacon specification to standardize the beacon as an interface to asynchronously transfer http data from user agent to a web server prior to page load without negative performance impact.
MDN Web Docs Glossary: Definitions of Web-related terms
abstraction accessibility accessibility tree (aom) adobe flash ajax algorithm alignment container alignment subject alpha (alpha channel) alpn api apple safari application context argument aria arpa arpanet array ascii asynchronous atag attribute b bandwidth base64 baseline beacon bézier curve bidi bigint blink block block (css) block (scripting) block cipher mode of operation boolean boot2gecko bootstrap bounding box breadcrumb ...
Front-end web developer - Learn web development
modules javascript first steps (30–40 hour read/exercises) javascript building blocks (25–35 hour read/exercises) introducing javascript objects (25–35 hour read/exercises) client-side web apis (30–40 hour read/exercises) asynchronous javascript (25–35 hour read/exercises) web forms — working with user data time to complete: 40–50 hours prerequisites forms require html, css, and javascript knowledge.
Tips for authoring fast-loading HTML pages - Learn web development
use async and defer, if possible make the javascript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script tags.
Use JavaScript within a webpage - Learn web development
you can hardly ever predict just how long it will take for users or browsers to complete an process (especially asynchronous actions such as loading resources).
Test your skills: JSON - Learn web development
this has something to do with async code.
JavaScript — Dynamic client-side scripting - Learn web development
asynchronous javascript in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
HTML performance features - Learn web development
elements & attributes impacting performance the <picture> element the <video> element the <source> element the <img> srcset attribute responsive images preloading content with rel="preload" - (https://w3c.github.io/preload/ ) async / defer attributes <iframe> <object> <script> rel attribute conclusion previous overview: performance next in this module the "why" of web performance what is web performance?
What is web performance? - Learn web development
it is important to minimize the loading and response times, and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience.
Server-side web frameworks - Learn web development
deno is powered by tokio — a rust-based asynchronous runtime which lets it serve web pages faster.
Ember resources and troubleshooting - Learn web development
using the design patterns provided by the framework, a route using fetch() would look something like this: import route from '@ember/routing/route'; export default class myroute extends route { async model() { let response = await fetch('some/url/to/json/data'); let json = await response.json(); return { data: json }; } } see more information on specifying the route's model here.
Getting started with Svelte - Learn web development
<main> <h1>hello {name}!</h1> <p>visit the <a href="https://svelte.dev/tutorial">svelte tutorial</a> to learn how to build svelte apps.</p> </main> svelte also supports tags like {#if...}, {#each...}, and {#await...} — these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.
Introducing a complete toolchain - Learn web development
parcel also installs the dependencies that we will use in our code, including react, react-dom, react-async-hook, date-fns, and format-number.
Gecko info for Windows accessibility vendors
ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load.
Experimental features in Firefox
nightly 71 yes developer edition 71 no beta 71 no release 71 no preference name dom.media.mediasession.enabled asynchronous sourcebuffer add and remove this adds the promise-based methods appendbufferasync() and removeasync() for adding and removing media source buffers to the sourcebuffer interface.
Frame script environment
sendasyncmessage() send an asynchronous message to chrome.
Limitations of chrome scripts
however, the domwindow is passed asynchronously, so by the time the chrome process receives it, the dom might have changed (for example, because code running in the content process modified it or we navigated to a different page).
Frame script environment
sendasyncmessage() send an asynchronous message to chrome.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
note that promise versions of browser api dom request methods also exist, so you can use async promise style syntax if you so wish.
mozbrowserclose
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserclose", function() { console.log("browser window has been closed; iframe will be destroyed."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsercontextmenu
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercontextmenu", function(event) { console.log("asking for menu:" + json.stringify(event.details)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserdocumentfirstpaint
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserdocumentfirstpaint", function() { console.log("first content painted."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsererror
notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfailure remotexul unsafecontenttype corruptedcontenterror certerror other example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsererror", function( event ) { console.log("an error occurred:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserfindchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserfindchange", function(event) { console.log("currently highlighted: " + event.details.activematchordinal + " out of " + event.details.numberofmatches); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserfirstpaint
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserfirstpaint", function(event) { console.log("first content painted."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsericonchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsericonchange", function( event ) { console.log("the url of the new favicon is:" + event.details.href); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserloadend
var browser = document.queryselector("iframe"); browser.addeventlistener('mozbrowserloadend',function(e) { stopreload.textcontent = 'r'; console.log(e.detail.backgroundcolor); controls.style.background = e.detail.backgroundcolor; }); browser.addeventlistener('mozbrowserloadend',function() { stopreload.textcontent = 'r'; }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserloadstart
var browser = document.queryselector("iframe"); browser.addeventlistener('mozbrowserloadstart',function() { stopreload.textcontent = 'x'; }); browser.addeventlistener('mozbrowserloadend',function() { stopreload.textcontent = 'r'; }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserlocationchange
var browser = document.queryselector("iframe"); browser.addeventlistener('mozbrowserlocationchange', function (event) { urlbar.value = event.detail.url; }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsermanifestchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermanifestchange", function(event) { console.log("new manifest url: " + event.details.href); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsermetachange
its name is " + event.details.name + ", and its content is " + event.details.content + "."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowseropensearch
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropensearch", function( event ) { console.log("new search engine encountered: " + event.details.title); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange ...
mozbrowseropentab
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowseropenwindow
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropenwindow", function( event ) { console.log("a new window has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserresize
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserresize", function( event ) { console.log("the new window size is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserscroll
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscroll", function( event ) { console.log("the new scroll position is " + event.details.left + " across and " + event.details.top + "down."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserscrollareachanged
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollareachanged", function( event ) { console.log("the new scroll area is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsersecuritychange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsersecuritychange", function( event ) { console.log("the ssl state is:" + event.details.state); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserselectionstatechanged
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserselectionstatechanged", function( event ) { if(event.details.visible) { console.log("the current selection is visible."); } else { console.log("the current selection is not visible."); } }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsershowmodalprompt
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsershowmodalprompt", function( event ) { console.log("asking for prompt:" + json.stringify(event.detail)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowsertitlechange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsertitlechange", function( event ) { console.log("the title of the document is:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowserusernameandpasswordrequired ...
mozbrowserusernameandpasswordrequired
example var browser = document.queryselector("iframe[mozbrowser]"); browser.addeventlistener("mozbrowserusernameandpasswordrequired", function( event ) { console.log("the auth realm is:" + event.detail.realm); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange ...
mozbrowservisibilitychange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("the browser is visible."); } else { console.log("the browser is hidden."); } }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange ...
Addon
this will perform asynchronously and deliver results to the given listener.
Add-on Repository
these searches are asynchronous; results are passed to the provided searchcallback object when the search is completed.
DownloadLastDir.jsm
to set the path, use setfile: // file is an nsifile downloadlastdir.setfile(uri, file); to retrieve the path in firefox 26 or later, use getfileasync: downloadlastdir.getfileasync(uri, function (file) { // file is an nsifile console.log(file); }); deprecated since gecko 26.0 to retrieve the path in firefox 25 or earlier, use getfile: // file is an nsifile var file = gdownloadlastdir.getfile(uri); console.log(file); private browsing mode when browsing normally, the browser uses the browser.download.lastdir preference to store the last...
OS.File.Info
using os.file.info example: determining if a file is a regular file the following snippet uses the main thread api to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| if (info.isdir) { // |somepath| represents a directory } else if (info.issymlink) { // |somepath| represents a symbolic link } else { // |somepath| represents a ...
Examples
function promisevalueaftertimeout(avalue, atimeout) { let deferred = promise.defer(); try { // an asynchronous operation will trigger the resolution of the promise.
Promise
a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api.
Promise.jsm
a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api.
BloatView
== bloatview: all (cumulative) leak and bloat statistics, tab process 1862 |<----------------class--------------->|<-----bytes------>|<----objects---->| | | per-inst leaked| total rem| 0 |total | 17 2484|253953338 38| 17 |asynctransactiontrackersholder | 40 40| 10594 1| 78 |compositorchild | 472 472| 1 1| 79 |condvar | 24 48| 3086 2| 279 |messagepump | 8 8| 30 1| 285 |mutex | 20 60| 89987 3| ...
Investigating leaks using DMD heap scan mode
that gave a result that contained this: 0x7f0882fe3230 [fragmentorelement (xhtml) script [...] --[mnodeinfo]--> 0x7f0897431f00 [nodeinfo (xhtml) script] [...] --[mloadingasyncrequests]--> 0x7f0892f29630 [scriptloadrequest] this confirms that this block is actually a scriptloadrequest.
GPU performance
doing performance work with gpus is harder than with cpus because of the asynchronous and massively parallel architecture.
MailNews automated testing
testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators.
MailNews
asynctestutils extended framework the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird.
NSS 3.44 release notes
package() crash with netscape certificate sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variable...
Hacking Tips
using rr on a test get the command line for your test run using -s: ./jit_test.py -s $js_shell saved-stacks/async.js insert 'rr' before the shell invocation: rr $js_shell -f $js_src/jit-test/lib/prolog.js --js-cache $js_src/jit-test/.js-cache -e "const platform='linux2'; const libdir='$js_src/jit-test/lib/'; const scriptdir='$js_src/jit-test/tests/saved-stacks/'" -f $js_src/jit-test/tests/saved-stacks/async.js (note that the above is an example; simply setting js_shell and js_src will not work).
JS::CompileOptions
forceasync bool false means js::cancompileoffthread may returns false depends on the length of the code.
JS_SetInterruptCallback
js_setinterruptcallback sets a callback that can be called asynchronously.
JS_SetOperationCallback
js_setoperationcallback sets a callback that can be called asynchronously.
SpiderMonkey 45
1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::exceptionstackornull (bug 814497) js::copyasyncstack (bug 1160307) js::getsavedframesource (bug 1216819) js::getsavedframeline (bug 1216819) js::getsavedframecolumn (bug 1216819) js::getsavedframefunctiondisplayname (bug 1216819) js::getsavedframeasynccause (bug 1216819) js::getsavedframeasyncparent (bug 1216819) js::getsavedframeparent (bug 1216819) js::buildstackstring (bug 1133191) js::flushperformancemonitoring (bug 1181175) js::...
TPS Tests
for example, consider the first action in the phase above: [bookmarks.add, bookmarks_initial] you could rewrite this as a custom function so as to add some custom logging: [async () => { logger.loginfo("adding bookmarks_initial"); await bookmarks.add(bookmarks_initial); }] note that this is probably best used for debugging, and new tests that want custom behavior should add it to the tps addon so that other tests can use it.
Redis Tips
in node, create client with explicit host and port like so: > var r = require('redis').createclient(6379, '127.0.0.1') commands are asynchronous.
Gecko events
is supported: yes event_asynch_show a hidden object is shown -- this is a layout occurance and is thus asynchronous is supported: yes event_asynch_hide an object is hidden -- this is a layout occurance and is thus asynchronous is supported: yes event_asynch_significant_change an object had a significant layout change which could affect the type of accessible object -- this is a layout occurance and is thus asynchronous ...
Feed content access API
however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync().
Places Developer Guide
d: function getfromvisit(visit_id) { var sql = <cdata><![cdata[ select from_visit from moz_places, moz_historyvisits where moz_historyvisits.id = :visit_id and moz_places.id = moz_historyvisits.place_id; ]]></cdata>.tostring(); var sql_stmt = getplacesdbconn.createstatement(sql); sql_stmt.params.visit_id = visit_id; var from_visit; try { // here we can't use the "executeasync" method since have to return a // result right-away.
Places Expiration
all of expiration uses the storage async api, that ensures i/o is in a separate thread, plus it won't block any read thanks to the use of the wal journaling system.
xpcshell
js> see also howto for common problems in writing xpcshell scripts, e.g., doing async network calls or using js modules.
imgIEncoder
1.0 66 introduced gecko 1.8 inherits from: nsiasyncinputstream last changed in gecko 1.9 (firefox 3) method overview void addimageframe( [array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 frameformat, in astring frameoptions); void encodeclipboardimage(in nsiclipboardimage aclipboardimage, out nsifile aimagefile); obsolete since gecko 1.9 void endimageencode(); void initfromdata([array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 inputformat, in astring outputoptions); voi...
imgIRequest
note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest().
mozIStorageBindingParams
the mozistoragebindingparams interface is used to bind values to parameters prior to calling mozistoragestatement.executeasync().
mozIStorageFunction
if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
mozIStoragePendingStatement
the mozistoragependingstatement interface represents a pending asynchronous database statement, and offers the cancel() method which allows you to cancel the pending statement.
nsIAuthInformation
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the caller of nsiauthprompt2.promptusernameandpassword() or nsiauthprompt2.promptpasswordasync() provides an object implementing this interface; the prompt implementation can then read the values here to prefill the dialog.
nsICacheService
note: starting in gecko 2.0, cache i/o is handled asynchronously.
nsIContentFrameMessageManager
frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging apis see the documentation for the nsicontentframemessagemanager's parent classes nsisyncmessagesender and nsimessagesender.
nsIContentPrefService
use the asynchronous interface nsicontentprefservice2 instead.
nsIDOMMozNetworkStatsManager
constants constant type description wifi long constant for wifi, set to 0 mobile long constant for mobile, set to 1 methods getsamples() asynchronously queries network interface statistics.
nsIDownloadManager
adding downloads to the download manager is now an asynchronous operation.
nsIEventTarget
method for posting an asynchronous event to the event target.
nsIFilePicker
open() opens the file dialog asynchrounously.
nsIHttpServer
* * @param callback * an asynchronous callback used to notify the user when this server is * stopped and all pending requests have been fully served * @throws ns_error_null_pointer * if callback is null * @throws ns_error_unexpected * if this server is not running */ void stop(in nsihttpserverstoppedcallback callback); /** * associates the local file represented by the string file with all reque...
nsIMessageBroadcaster
methods void broadcastasyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects); nsimessagelistenermanager getchildat(in unsigned long aindex); broadcastasyncmessage() like sendasyncmessage(), but also broadcasts this message to all "child" message managers of this message manager.
nsIMessageListener
this function receives a message from one of the three message-sending functions in the message manager framework: broadcastasyncmessage sendasyncmessage sendsyncmessage.
nsIMsgFolder
manyheaderstodownload boolean readonly: used to determine if it will take a long time to download all the headers in this folder - so that we can do folder notifications synchronously instead of asynchronously.
nsIMsgMessageService
this is an async operation of course.note: you must pass in a url listener in order to figure out when the operation is done.
nsIMsgProtocolInfo
folderscreateasync boolean new in thunderbird 24 (bug 832034) preflightprettynamewithemailaddress boolean unused.
nsINavHistoryContainerResultNode
state_loading 1 the container has been opened asynchronously, but is still loading and is not all the way opened yet.
nsINavHistoryService
you should use the new async api moziasynchistory.updateplaces() instead.
nsIOutputStream
note: a non-blocking output stream may implement nsiasyncoutputstream to provide consumers with a way to wait for the stream to accept more data once its write() method is unable to accept any data without blocking.
nsIProtocolHandler
uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data.
nsISocketTransportService
the notification is asynchronous, delivered via the given nsirunnable instance on the socket transport thread.
nsISyncMessageSender
jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); jsval sendrpcmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); sendsyncmessage() like sendasyncmessage(), except blocks the sender until all listeners of the message have been invoked.
nsITelemetry
val getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscal...
nsIThread
consider use asynchronous callbacks instead.
nsIUploadChannel
the upload stream may only be set prior to the invocation of asyncopen on the channel.
nsIWebProgress
the nsiwebprogress interface is used to add or remove nsiwebprogresslistener instances to observe the loading of asynchronous requests (usually in the context of a dom window).
nsIWebSocketListener
netwerk/protocol/websocket/nsiwebsocketlistener.idlscriptable implement this interface to receive websocket traffic events asynchronously after calling nsiwebsocketchannel.asyncopen().
nsIXULTemplateQueryProcessor
if the query processor needs to load the datasource asynchronously, it may set the ashoulddelaybuilding returned parameter to true to delay building the template content, and call the builder's rebuild method when the data is available.
nsIZipWriter
if the operation is performed on the queue then the channel will be opened asynchronously, otherwise the channel must support being opened synchronously.
nsIMsgCloudFileProvider
constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider.
Gloda examples
this requires two chained asynchronous calls: //first take an email address and turn it into an identity object id_q = gloda.newquery(gloda.noun_identity); id_q.kind("email"); id_q.value("test@example.com"); id_coll = id_q.getcollection({ onitemsadded: function _onitemsadded(aitems, acollection) { }, onitemsmodified: function _onitemsmodified(aitems, acollection) { ...
Index
this may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onstart/stoprunningurl notifications when the url starts/stops, etc.
Mailbox
this may seem like a lot of infrastructure just to read messages from a flat file, but it allows us to do it asynchronously, and to have reading local messages fit into the same kind of mechanisms that reading nntp and imap messages do - running urls, getting onstart/stoprunningurl notifications when the url starts/stops, etc.
Add to iPhoto
this.struct_lsapplicationparameters = new ctypes.structtype('lsapplicationparameters', [ {'version': cfindex}, {'flags': optionbits}, {'application': ctypes.voidptr_t}, // fsref of application to launch {'asynclaunchrefcon': ctypes.voidptr_t}, {'environment': ctypes.voidptr_t}, // cfdictionaryref {'argv': ctypes.voidptr_t}, // cfarrayref of args {'initialevent': ctypes.voidptr_t}]); // appleevent * most of these fields, we won't be using.
ctypes.open
ed, this will be addon xpi } this can then be joined with your file name to obtain it's path like this: function startup(adata, areason) { var jarpath_folder = 'jar:' + os.path.tofileuri(adata.installpath.path) + '!/'; // if unpacked is false in install.rdf this will look like: "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aksozfjt.unnamed%20profile%2010/extensions/asynczip@jetpack!/" var filepath_folder = adata.installpath.path; // if unpacked is set to false in install.rdf this will look like: "c:\users\vayeate\appdata\roaming\mozilla\firefox\profiles\aksozfjt.unnamed profile 10\extensions\asynczip@jetpack" var filepath_mylib = os.path.join(filepath_folder, 'mysubfolder', 'mycfunctionsforunix.so'); var jarpath_mylib = jarpath_folder + 'mysubfolder/...
Browser Side Plug-in API - Plugins
npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated).
Drawing and Event Handling - Plugins
if a plug-in calls one of these methods, it receives a paint message asynchronously.
Streams - Plugins
after this data is copied from the browser's buffer to the plug-in's buffer, the plug-in begins to process the data asynchronously.
Gecko Plugin API Reference - Plugins
npn_pluginthreadasynccall thread-safe way to request that the browser calls a plug-in function on the browser or plug-in thread (the thread on which the plug-in was initiated).
Debugger.Script - Firefox Developer Tools
isasyncfunction true if this instance refers to a jsscript for an async function, defined with an async function expression or statement.
Network request list - Firefox Developer Tools
open in new tab resends the request in a new tab — very useful for debugging asynchronous requests.
Intensive JavaScript - Firefox Developer Tools
the main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging api.
Animation.pending - Web APIs
WebAPIAnimationpending
the read-only animation.pending property of the web animations api indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
Animation.playState - Web APIs
previously, web animations defined a pending value to indicate that some asynchronous operation such as initiating playback was yet to complete.
Animation.updatePlaybackRate() - Web APIs
updateplaybackrate() is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump.
Animation - Web APIs
WebAPIAnimation
animation.pending read only indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
BaseAudioContext.createBuffer() - Web APIs
the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode.
BaseAudioContext.decodeAudioData() - Web APIs
the decodeaudiodata() method of the baseaudiocontext interface is used to asynchronously decode audio file data contained in an arraybuffer.
BaseAudioContext - Web APIs
baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer.
Using the Beacon API - Web APIs
the beacon interface schedules an asynchronous and non-blocking request to a web server.
CanvasRenderingContext2D.drawWindow() - Web APIs
drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have.
Client.postMessage() - Web APIs
examples sending a message from a service worker to a client: addeventlistener('fetch', event => { event.waituntil(async function() { // exit early if we don't have access to the client.
Clients - Web APIs
WebAPIClients
addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await clients.matchall({ includeuncontrolled: true }); let chatclient; // let's see if we already have a chat window open: for (const client of allclients) { const url = new url(client.url); if (url.pathname == '/chat/') { // excellent, let's use it!
Clipboard.read() - Web APIs
WebAPIClipboardread
note: the asynchronous clipboard and permissions apis are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like.
Clipboard.write() - Web APIs
WebAPIClipboardwrite
note: browser support for the asynchronous clipboard apis is still in the process of being implemented.
Clipboard.writeText() - Web APIs
note: browser support for the asynchronous clipboard apis is still in the process of being implemented.
ClipboardItem() - Web APIs
async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } specifications specification ...
ClipboardItem.getType() - Web APIs
async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications ...
ClipboardItem.types - Web APIs
async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications ...
ConvolverNode - Web APIs
let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ...
Document: DOMContentLoaded event - Web APIs
if you want the dom to get parsed as fast as possible after the user has requested the page, you can make your javascript asynchronous and optimize loading of stylesheets.
Document.currentScript - Web APIs
syntax var curscriptelement = document.currentscript; example this example checks to see if the script is being executed asynchronously: if (document.currentscript.async) { console.log("executing asynchronously"); } else { console.log("executing synchronously"); } view live examples specifications specification status comment html living standardthe definition of 'document.currentscript' in that specification.
Document.exitPointerLock() - Web APIs
the exitpointerlock() method asynchronously releases a pointer lock previously requested through element.requestpointerlock.
Document.write() - Web APIs
WebAPIDocumentwrite
note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchronously-loaded external script was ignored" in the error console.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
elem.addeventlistener('click', async evt => { const animation = elem.animate( { transform: `translate(${evt.clientx}px, ${evt.clienty}px)` }, { duration: 800, fill: 'forwards' } ); await animation.finished; // commitstyles will record the style up to and including `animation` and // update elem’s specified style with the result.
Element: DOMMouseScroll event - Web APIs
the dom dommousescroll event is fired asynchronously when mouse wheel or similar device is operated and the accumulated scroll amount is over 1 line or 1 page since last event.
Element: MSManipulationStateChanged event - Web APIs
examples // listen for panning state change events outerscroller.addeventlistener("msmanipulationstatechanged", function(e) { // check to see if they lifted while pulled to the top if (e.currentstate == ms_manipulation_state_inertia && outerscroller.scrolltop === 0) { refreshitemsasync(); } }); specifications not part of any specification.
Element: MozMousePixelScroll event - Web APIs
the firefox-only, non-standard, and obsolete mozmousepixelscroll event is fired at an element asynchronously when a mouse wheel or similar device is operated.
Element: blur event - Web APIs
bubbles no cancelable no interface focusevent event handler property onblur sync / async sync composed yes examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event...
Element: focus event - Web APIs
bubbles no cancelable no interface focusevent event handler property onfocus sync / async sync composed yes examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result ...
Element: focusin event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusin sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specifica...
Element: focusout event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusout sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specificati...
Element: mousewheel event - Web APIs
the obsolete and non-standard mousewheel event is fired asynchronously at an element to provide updates while a mouse wheel or similar device is operated.
Element.requestFullscreen() - Web APIs
the element.requestfullscreen() method issues an asynchronous request to make the element be displayed in full-screen mode.
Element.requestPointerLock() - Web APIs
the element.requestpointerlock() method lets you asynchronously ask for the pointer to be locked on the given element.
Event - Web APIs
WebAPIEvent
clicking the mouse button or tapping keyboard, or generated by apis to represent the progress of an asynchronous task.
EventTarget.dispatchEvent() - Web APIs
notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously.
ExtendableEvent.waitUntil() - Web APIs
example using waituntil() within a service worker's install event: addeventlistener('install', event => { const precache = async () => { const cache = await caches.open('static-v1'); return cache.addall([ '/', '/about/', '/static/styles.css' ]); }; event.waituntil(precache()); }); specifications specification status comment service workersthe definition of 'waituntil()' in that specification.
FetchEvent.preloadResponse - Web APIs
addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network.
FetchEvent.navigationPreload - Web APIs
addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network.
FetchEvent.respondWith() - Web APIs
event.respondwith(async function() { // try to get the response from a cache.
FileError - Web APIs
WebAPIFileError
in the file system api, a fileerror represents error conditions that you might encounter while accessing the file system using the asynchronous api.
FileReader - Web APIs
the filereader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using file or blob objects to specify the file or data to read.
FileHandle API - Web APIs
periodically, the results of those operation are asynchronously flushed to the device storage area.
File and Directory Entries API support in Firefox - Web APIs
only the asynchronous versions of the interfaces are implemented.
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with css class document.body.classlist.add('fonts-loaded'); } specifications specification status comment css font loading module level 3the definitio...
GeolocationCoordinates.longitude - Web APIs
this is an asynchronous request, so we provide a callback which receives as in put a geolocationposition object describing the determined position.
Using the Geolocation API - Web APIs
this initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information.
GlobalEventHandlers.onmousewheel - Web APIs
the mousewheel event is fired asynchronously when a mouse wheel or similar device is operated.
Audio() - Web APIs
if a url is specified, the browser begins to asynchronously load the media resource before returning the new object.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
ode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfascallback = function(iconname) { return function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputstream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asynccopy(instream, outstream, netutilcallback()); } } canvas.mozfetchasstream(mfascallback('myicon'), 'image/vnd.microsoft.icon'); specifications not part of any specification.
HTMLElement: beforeinput event - Web APIs
bubbles yes cancelable yes interface inputevent event handler property none sync / async sync composed yes default action update the dom element examples this example logs current value of the element immediately before replacing that value with the new one applied to the <input> element.
HTMLImageElement - Web APIs
if this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously, or auto to indicate no preference (which is the default).
HTMLMediaElement.play() - Web APIs
example this example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: let videoelem = document.getelementbyid("video"); let playbutton = document.getelementbyid("playbutton"); playbutton.addeventlistener("click", handleplaybutton, false); playvideo(); async function playvideo() { try { await videoelem.play(); playbutton.classlist.add("playing"); } catch(err) { playbutton.classlist.remove("playing"); } } function handleplaybutton() { if (videoelem.paused) { playvideo(); } else { videoelem.pause(); playbutton.classlist.remove("playing"); } } in this example, playback of video is toggled off and on by the async pla...
HTMLMediaElement.seekToNextFrame() - Web APIs
the htmlmediaelement.seektonextframe() method asynchronously advances the the current play position to the next frame in the media.
In depth: Microtasks and the JavaScript runtime environment - Web APIs
this is further alleviated by using asynchronous javascript techniques such as promises to allow the main code to continue to run while waiting for the results of a request.
HTML Drag and Drop API - Web APIs
a key difference between the datatransfer and datatransferitem interfaces is that the former uses the synchronous getdata() method to access a drag item's data, but the latter instead uses the asynchronous getasstring() method.
History.back() - Web APIs
WebAPIHistoryback
this method is asynchronous.
History.forward() - Web APIs
WebAPIHistoryforward
this method is asynchronous.
History.go() - Web APIs
WebAPIHistorygo
this method is asynchronous.
IDBCursor - Web APIs
WebAPIIDBCursor
the cursor enables an application to asynchronously process all the records in the cursor's range.
IDBCursorWithValue - Web APIs
the cursor enables an application to asynchronously process all the records in the cursor's range.
IDBDatabase - Web APIs
example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase).
IDBEnvironment - Web APIs
properties idbenvironment.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; contains an idbfactory object.
IDBFactory.deleteDatabase() - Web APIs
the method returns an idbopendbrequest object immediately, and performs the deletion operation asynchronously.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
the method returns an idbopendbrequest object immediately, and performs the open operation asynchronously.
IDBFactory - Web APIs
the idbfactory interface of the indexeddb api lets applications asynchronously access the indexed databases.
IDBIndex - Web APIs
WebAPIIDBIndex
idbindex interface of the indexeddb api provides asynchronous access to an index in a database.
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions.
IDBTransaction - Web APIs
the idbtransaction interface of the indexeddb api provides a static, asynchronous transaction on a database using event handler attributes.
ImageBitmap - Web APIs
imagebitmap provides an asynchronous and resource efficient pathway to prepare textures for rendering in webgl.
IntersectionObserver - Web APIs
the intersectionobserver interface of the intersection observer api provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
Timing element visibility with the Intersection Observer API - Web APIs
the intersection observer api makes it easy to be asynchronously notified when elements of interest become more or less obscured by a shared ancestor node or element, including the document itself.
LocalFileSystemSync - Web APIs
for more concepts, see the counterpart article for the asynchronous api.
MediaDevices.getDisplayMedia() - Web APIs
async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } this uses await to asynchronously wait for getdisplaymedia() to resolve with a mediastream which contains the display contents as requested by the...
MediaDevices.getUserMedia() - Web APIs
generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.mediadevices.getusermedia(constraints); /* use the stream */ } catch(err) { /* handle the error */ } } similarly, using the raw promises directly, the code looks like this: navigator.mediadevices.getusermedia(constraints) .then(function(stream) { /* use the stream */ }) .catch(function(err...
MediaRecorder: error event - Web APIs
examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { co...
MediaTrackSupportedConstraints.cursor - Web APIs
async function capturewithcursor() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { displaysurface: "browser" }, audio: false; }; if (supportedconstraints.cursor) { displaymediaoptions.video.cursor = "always"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediao...
MediaTrackSupportedConstraints.displaySurface - Web APIs
async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.displaysurface) { displaymediaoptions.video.displaysurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) {...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.logicalsurface) { displaymediaoptions.video.logicalsurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) {...
Media Capture and Streams API (Media Stream) - Web APIs
it provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process.
Navigator.clipboard - Web APIs
use of the asynchronous clipboard read and write methods requires that the user grant the web site or app permission to access the clipboard.
Navigator.share() - Web APIs
WebAPINavigatorshare
the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.textcontent = 'mdn shared successfully' } catch(err) { resultpara.textcontent = 'error: ' + err } }); sharing files to share files, first test for and call navigator.canshare().
Navigator - Web APIs
WebAPINavigator
navigator.sendbeacon() used to asynchronously transfer a small amount of data using http from the user agent to a web server.
Notification - Web APIs
these notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user.
NotificationAction - Web APIs
these buttons' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously show actions to the user in a notification.
OffscreenCanvas - Web APIs
// commit rendering to the second canvas var bitmaptwo = offscreen.transfertoimagebitmap(); two.transferfromimagebitmap(bitmaptwo); asynchronous display of frames produced by an offscreencanvas another way to use the offscreencanvas api, is to call transfercontroltooffscreen() on a <canvas> element, either on a worker or the main thread, which will return an offscreencanvas object from an htmlcanvaselement object from the main thread.
PaymentAddress - Web APIs
onation", amount: { currency: "usd", value: "65.00" } }, displayitems: [ { label: "original donation amount", amount: { currency: "usd", value: "65.00" }, }, ], shippingoptions: [ { id: "standard", label: "standard shipping", amount: { currency: "usd", value: "0.00" }, selected: true, }, ], }; const options = { requestshipping: true }; async function dopaymentrequest() { const request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
PaymentRequest.onmerchantvalidation - Web APIs
examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentResponse.onpayerdetailchange - Web APIs
response.onpayerdetailchange = async ev => { const promisestovalidate = []; const { payername, payeremail, payerphone } = response; // validate each value which changed by calling a function // that validates each type of data, returning a promise which // resolves if the data is valid.
PerformanceTiming.domInteractive - Web APIs
nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts.
Pointer Lock API - Web APIs
here is an example of using pointerlockelement: if(document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); } else { console.log('the pointer lock status is now unlocked'); } the document.exitpointerlock() method is used to exit pointer lock, and like requestpointerlock, works asynchronously using the pointerlockchange and pointerlockerror events, which you'll see more about below.
PushSubscription - Web APIs
pushsubscription.unsubscribe() starts the asynchronous process of unsubscribing from the push service, returning a promise that resolves to a boolean when the current subscription is successfully unregistered.
Push API - Web APIs
WebAPIPush API
this lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.
RTCDTMFSender.insertDTMF() - Web APIs
sending of the tones is performed asynchronously, with tonechange events sent to the rtcdtmfsender every time a tone starts or ends.
RTCDataChannel.bufferedAmount - Web APIs
the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously.
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously.
RTCDataChannel.close() - Web APIs
most of the process of closing the connection is handled asynchronously; you can detect when the channel has finished closing by watching for a close event on the data channel.
RTCRtpReceiver.getStats() - Web APIs
the rtcrtpreceiver method getstats() asynchronously requests an rtcstatsreport object which provides statistics about incoming traffic on the owning rtcpeerconnection, returning a promise whose fulfillment handler will be called once the results are available.
RTCRtpSender.getStats() - Web APIs
the rtcrtpsender method getstats() asynchronously requests an rtcstatsreport object which provides statistics about outgoing traffic on the rtcpeerconnection which owns the sender, returning a promise which is fulfilled when the results are available.
ReadableStreamDefaultReader.read() - Web APIs
async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder("utf-8"); let response = await fetch(fileurl); let reader = response.body.getreader(); let {value: chunk, done: readerdone} = await reader.read(); chunk = chunk ?
SVGImageElement.decode - Web APIs
the decode() method of the svgimageelement interface initiates asynchronous decoding of an image, returning a promise that resolves once the image data is ready for use.
SVGImageElement.decoding - Web APIs
async: decode the image asynchronously to reduce delay in presenting other content.
SVGImageElement - Web APIs
svgimageelement.decode() initiates asynchronous decoding of the image data.
ServiceWorkerContainer: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ...
ServiceWorkerGlobalScope - Web APIs
additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used.
Service Worker API - Web APIs
it is designed to be fully async; as a consequence, apis such as synchronous xhr and localstorage can't be used inside a service worker.
SourceBuffer.abort() - Web APIs
the mse api is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense.
SpeechSynthesis.onvoiceschanged - Web APIs
the onvoiceschanged property of the speechsynthesis interface represents an event handler that will run when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices() method has changed (when the voiceschanged event fires.) this may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.
StorageManager.estimate() - Web APIs
this method operates asynchronously, so it returns a promise which resolves once the information is available.
SubtleCrypto.encrypt() - Web APIs
crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-ctr", counter, length: 64 }, key, encoded ); } let iv = new uint8array(16); let key = new uint8array(16); let data = new uint8array(12345); //crypto functions are wrapped in promises so we have to use await and make sure the function that //contains this code is an async function //encrypt function wants a cryptokey object const key_encoded = await crypto.subtle.importkey( "raw", key.buffer, 'aes-ctr' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc t...
TransformStream - Web APIs
async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk)) controller.enqueue(new uint8array(chunk.buffer, chunk.byteoffset, chunk.bytelength)) else if (array.isarray(chunk) && chunk.every(value...
USBDevice.claimInterface() - Web APIs
async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'claiminterface()' in that specification.
USBDevice.configuration - Web APIs
async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'configuration' in that specification.
USBDevice.opened - Web APIs
WebAPIUSBDeviceopened
async setdevicecolor(usbdevice, r, g, b) { if (device.opened) { // this hypothetical usb device requires that the data passed to // it be in a uint8array.
WebGL2RenderingContext.beginQuery() - Web APIs
the webgl2renderingcontext.beginquery() method of the webgl 2 api starts an asynchronous query.
WebGL2RenderingContext.createQuery() - Web APIs
the webgl2renderingcontext.createquery() method of the webgl 2 api creates and initializes webglquery objects, which provide ways to asynchronously query for information.
WebGLQuery - Web APIs
the webglquery interface is part of the webgl 2 api and provides ways to asynchronously query for information.
Compressed texture formats - Web APIs
no examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_...
Signaling and video calling - Web APIs
note: the onicecandidate event and createanswer() promise are both async calls which are handled separately.
Writing WebSocket client applications - Web APIs
as establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a websocket object will be successful.
The WebSocket API (WebSockets) - Web APIs
jsonrpc-bidirectional: asynchronous rpc which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client).
Using bounded reference spaces - Web APIs
you can create a session that supports a bounded-floor reference space if available by using code such as the following: async function onactivatexrbutton(event) { if (!xrsession) { navgator.xr.requestsession("immersive-vr"), { requiredfeatures: ["local-floor"], optionalfeatures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, exiting a...
Movement, orientation, and motion: A WebXR example - Web APIs
async function onxrbuttonclick(event) { if (!xrsession) { navigator.xr.requestsession(session_type) .then(sessionstarted); } else { await xrsession.end(); if (xrsession) { sessionended(); } } } this begins by looking at the value of xrsession to see if we already have a xrsession object representing an ongoing webxr session.
Rendering and the WebXR frame animation callback - Web APIs
kicking off the renderer thus looks like this: let worldrefspace; async function runxr(xrsession) { worldrefspace = await xrsession.requestreferencespace("immersive-vr"); if (worldrefspace) { viewerrefspace = worldrefspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsession.requestanimationframe(mydrawframe); } } after getting a reference space for the immersive worl...
Background audio processing using AudioWorklet - Web APIs
to use an audio worklet processor, you can use code similar to the following: let audiocontext = null; async function createmyaudioprocessor() { if (!audiocontext) { try { audiocontext = new audiocontext(); await audiocontext.resume(); await audiocontext.audioworklet.addmodule("module-url/module.js"); } catch(e) { return null; } } return new audioworkletnode(audiocontext, "processor-name"); } this createmyaudioprocessor() function creates and returns a new in...
Web Speech API - Web APIs
the web speech api has two parts: speechsynthesis (text-to-speech), and speechrecognition (asynchronous speech recognition.) web speech concepts and usage the web speech api makes web apps able to handle voice data.
Window: blur event - Web APIs
WebAPIWindowblur event
bubbles no cancelable no interface focusevent event handler property onblur sync / async sync composed yes examples live example this example changes the appearance of a document when it loses focus.
Window: focus event - Web APIs
bubbles no cancelable no interface focusevent event handler property onfocus sync / async sync composed yes examples live example this example changes the appearance of a document when it loses focus.
Window.open() - Web APIs
WebAPIWindowopen
the window creation and the loading of the referenced resource are done asynchronously.
window.postMessage() - Web APIs
as with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an exception.
Window - Web APIs
WebAPIWindow
windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object.
WindowOrWorkerGlobalScope.indexedDB - Web APIs
the indexeddb read-only property of the windoworworkerglobalscope mixin provides a mechanism for applications to asynchronously access the capabilities of indexed databases.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object.
WorkerGlobalScope - Web APIs
windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object.
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
can be used with document.async to indicate whether the request is synchronous or asynchronous (the default).
XMLDocument - Web APIs
y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="441" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">xmldocument</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} property also inherits properties from: document xmldocument.async used with xmldocument.load() to indicate an asynchronous request.
Sending and Receiving Binary Data - Web APIs
firefox-specific examples this example transmits binary content asynchronously, using the post method, and firefox's non-standard sendasbinary().
XMLHttpRequest.multipart - Web APIs
all requests must be asynchronous.
XMLHttpRequest.responseText - Web APIs
while handling an asynchronous request, the value of responsetext always has the current content received from the server, even if it's incomplete because the data has not been completely received yet.
XMLHttpRequest.responseType - Web APIs
xmlhttprequests are asynchronous by default; they are only placed in synchronous mode by passing false as the value of the optional async parameter when calling open().
XMLHttpRequest.responseXML - Web APIs
if the responsetype is set to "document" and the request was made asynchronously, instead the response is parsed as "text/html".
XMLHttpRequest.send() - Web APIs
if the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.
XMLHttpRequest.timeout - Web APIs
using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method.
XMLHttpRequest - Web APIs
if the request is asynchronous (which is the default), this method returns as soon as the request is sent.
XRSession.cancelAnimationFrame() - Web APIs
const xr = navigator.xr; let requesthandle = null; let xrsession = null; if (xr) { xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { startxr(); } }); } function framecallback(time, xrframe) { xrsession.requestanimationframe(framecallback); // update and render the frame } async function startxr() { xrsession = xr.requestsession("immersive-vr"); if (xrsession) { stopbutton.onclick = stopxr; requesthandle = xrsession.requestanimationframe(framecallback); } } function pausexr() { if (xrsession && requesthandle) { xrsession.cancelanimationframe(requesthandle); requesthandle = null; } } specifications specification status commen...
An overview of accessible web applications and widgets - Accessibility
asynchronous content changes under construction.
WAI ARIA Live Regions/API Support - Developer guides
this information is retrieved differently on each platform, because some platforms use asynchronous events.
Overview of events and handlers - Developer guides
there is also some subtlety in learning how to write the handler functions since such code works asynchronously and potentially will run repeatedly but in slightly different situations.
Event developer guide - Developer guides
WebGuideEvents
events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.
HTML5 - Developer guides
WebGuideHTMLHTML5
xmlhttprequest level 2 allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions.
Developer guides
events developer guide events refer to two things: a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page; and the naming, characterization, and use of a large number of incidents of different types.
HTML attribute reference - HTML: Hypertext Markup Language
async <script> executes the script asynchronously.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
async decode the image asynchronously, to reduce delay in presenting other content.
Cache-Control - HTTP
stale-while-revalidate=<seconds> indicates the client will accept a stale response, while asynchronously checking in the background for a fresh one.
HTTP Index - HTTP
WebHTTPIndex
it is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request.
202 Accepted - HTTP
WebHTTPStatus202
202 is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request.
HTTP response status codes - HTTP
WebHTTPStatus
it is noncommittal, since there is no way in http to later send an asynchronous response indicating the outcome of the request.
JavaScript technologies overview - JavaScript
xmlhttprequest makes it possible to send asynchronous http requests.
Array.prototype.reduceRight() - JavaScript
value = callback(value, t[k], k, t); } } return value; }; } examples sum up all values within an array var sum = [0, 1, 2, 3].reduceright(function(a, b) { return a + b; }); // sum is 6 flatten an array of arrays var flattened = [[0, 1], [2, 3], [4, 5]].reduceright(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] run a list of asynchronous functions with callbacks in series each passing their results to the next const waterfall = (...functions) => (callback, ...args) => functions.reduceright( (composition, fn) => (...results) => fn(composition, ...results), callback )(...args); const randint = max => math.floor(math.random() * max) const add5 = (callback, x) => { settimeout(callback, randint(1000), x + 5); }...
Promise.prototype.catch() - JavaScript
hen(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch method most of the time var p1 = new promise(function(resolve, reject) { throw new error('uh-oh!'); }); p1.catch(function(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 = new promise(function(resolve, reject) { settimeout(function() { throw new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is never called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silen...
Promise.resolve() - JavaScript
true // value: 33 the inverted order of the logs is due to the fact that the then handlers are called asynchronously.
Symbol - JavaScript
static properties symbol.asynciterator a method that returns the default asynciterator for an object.
WebAssembly.Instance - JavaScript
le object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); this also demonstrates how the exports property is used to access exported funct...
JavaScript
asynchronous javascript discusses asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
CSS and JavaScript animation performance - Web Performance
to enable the omta (off main thread animation) in firefox, you can go to about:config and search for the layers.offmainthreadcomposition.async-animations.
Critical rendering path - Web Performance
performance tips include 1) minimizing the number of critical resources by deferring their download, marking them as async, or eliminating them altogether, 2) optimizing the number of requests required along with the file size of each request, and 3) optimizing the order in which critical resources are loaded by prioritizing the downloading critical assets, shorten the critical path length.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
let's explore all of these index.js the index.js file starts by registering the service worker: navigator.serviceworker.register('service-worker.js') .then(function(registration) { return registration.pushmanager.getsubscription() .then(async function(subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); it is a little bit more complicated than the service worker we saw in the js13kpwa demo.
Features restricted to secure contexts - Web security
api chrome/opera edge safari firefox async clipboard api 66 not supported not supported 63 background sync (see syncmanager, for example) 49 not supported not supported not supported cache-control: immutable not supported 15 11 49 credential management api 51 not supported not supported not supported generic sensor api 67 not supported not support...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
var testtransform = document.implementation.createdocument("", "test", null); // just an example to get a transform into a script as a dom // xmldocument.load is asynchronous, so all processing happens in the // onload handler testtransform.addeventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node.
Compiling a New C/C++ Module to WebAssembly - WebAssembly
file://your_path/hello.html), you will end up with an error message along the lines of both async and sync fetching of the wasm failed.
Caching compiled WebAssembly modules - WebAssembly
request = store.get(url); request.onerror = reject.bind(null, `error getting wasm module ${url}`); request.onsuccess = event => { if (request.result) resolve(request.result); else reject(`module ${url} was not found in wasm cache`); } }); } storing and instantiating modules next, we define a function storeindatabase() that fires off an async operation to store a given wasm module in a given database.