Search completed in 2.16 seconds.
933 results for "sync":
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 51 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.
... synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience.
...And 19 more matches
SyncEvent.SyncEvent() - Web APIs
the syncevent() constructor creates a new syncevent object.
... syntax var mysyncevent = new syncevent(type, init) parameters type the type of the event.
...options are as follows: tag: a developer-defined unique identifier for this syncevent.
... lastchance: a boolean indicating that the user agent will not make further synchronization attempts after the current attempt.
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 30 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 29 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 16 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 16 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 15 more matches
Address book sync client design
pizzarro <rhp@netscape.com> contents overview client side sync logic public interfaces overview there is an component available in the mozilla tree for performing synchronization operations against a server based address book.
... the general architecture for the sync component is the following: mozilla ui ab sync logic mork ab database sync protocol encoding sync protocol decoding http "post" api mozilla networking client side sync logic the client synchronization logic defers to the server peforming some intelligence in handling duplicate entries for the sync process.
... the static information that is held on the client for address book sync operations is stored in a file called absync.dat which is located in the root directory of the users profile information.
...And 15 more matches
LocalFileSystemSync - Web APIs
the localfilesystemsync interface of the file system api gives you access to a sandboxed file system.
... basic concepts you can request access to a sandboxed file system by requesting localfilesystemsync object from within a web worker.
... the global methods in the window object requestfilesystemsync() and resolvelocalfilesystemsyncurl() methods are exposed to the worker's global scope.
...And 12 more matches
FileSystemEntrySync - Web APIs
the filesystementrysync interface of the file and directory entries api represents an entry in a file system; it can be either a fileentrysync or directoryentry.
... basic concepts the filesystementrysync interface includes methods that you would expect for manipulating files and directories, but it also include a really handy method for getting a url of the entry: tourl().
... method overview metadata getmetadata () raises (fileexception); filesystementrysync moveto (in directoryentrysync parent, optional domstring newname) raises (fileexception); filesystementrysync copyto(in directoryentrysync parent, optional domstring newname) raises (fileexception); domstring tourl(); void remove() raises (fileexception); directoryentrysync getparent(); attributes attribute type description f...
...And 11 more matches
Firefox Sync
firefox sync is built into the desktop versions of firefox, as well as firefox for android and firefox for ios.
... firefox sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices.
... the exact types of information synced is user-configurable in the browser's preferences or options page.
...And 8 more matches
SyncManager.register() - Web APIs
the syncmanager.register method of the syncmanager interface returns a promise that resolves to a syncregistration instance.
... syntax syncmanager.register([options]).then(function(syncregistration) { ...
... }) returns a promise that resolves to an instance of syncregistration.
...And 8 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
Firefox Sync - Archive of obsolete content
components and services sync refers to a family of related components and services which provide synchronization of data between mozilla application instances.
... these components and services include: firefox sync client the sync client bundled with mozilla products.
... server a server implementation of the sync http protocol.
...And 7 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 - 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 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
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 7 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 7 more matches
WebGL2RenderingContext.clientWaitSync() - Web APIs
the webgl2renderingcontext.clientwaitsync() method of the webgl 2 api blocks and waits for a webglsync object to become signaled or a given timeout to be passed.
... syntax glenum gl.clientwaitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on.
...may be gl.sync_flush_commands_bit.
...And 7 more matches
IDBDatabaseSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the databasesync interface in the indexeddb api represents a synchronous connection to a database.
... method overview idbobjectstoresync createobjectstore (in domstring name, in domstring keypath, in optional boolean autoincrement) raises (idbdatabaseexception); idbobjectstoresync openobjectstore (in domstring name, in optional unsigned short mode) raises (idbdatabaseexception); void removeobjectstore (in domstring storename) raises (idbdatabaseexception); void setversion (in domstring version); idbtransactionsync transaction (in optional domstringlist storenames, in optional unsigned int timeout) raises (idbdatabaseexception); attributes attribute type description description readonly domstring the human-readable description of the connected database.
...And 6 more matches
IDBObjectStoreSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the idbobjectstoresync interface of the indexeddb api provides synchronous access to an object store of a database.
... method overview any add (in any value, in optional any key) raises (idbdatabaseexception); idbindexsync createindex (in domstring name, in domstring storename, in domstring keypath, in optional boolean unique); any get (in any key) raises (idbdatabaseexception); idbcursorsync opencursor (in optional idbkeyrange range, in optional unsigned short direction) raises (idbdatabaseexception); idbindexsync openindex (in domstring name) raises (idbdatabaseexception); any put (in any value, in optional any key) raises (idbdatabaseexception); void remove (in any key) raises (idbdatabaseexception); void removeindex (in domstring indexname) raises (idbdatabaseexception); attributes attribute type descriptio...
...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
DirectoryEntrySync - Web APIs
the directoryentrysync interface of the file system api represents a directory in a file system.
... example the getfile() method returns a fileentrysync, which represents a file in the file system.
... var fileentry = fs.root.getfile('seekrits.txt', {create: true}); the getdirectory() method returns a directoryentrysync, which represents a file in the file system.
...And 5 more matches
DirectoryReaderSync - Web APIs
the directoryreadersync interface of the file system api lets you read the entries in a directory.
... basic concepts before you call the only method in this interface, readentries(), create the directoryentrysync object.
... but directoryentrysync (as well as fileentrysync) is not a data type that you can pass between a calling app and web worker thread.
...And 5 more matches
FileReaderSync - Web APIs
the filereadersync interface allows to read file or blob objects synchronously.
... this interface is only available in workers as it enables synchronous i/o that could potentially block.
... methods filereadersync.readasarraybuffer() this method converts a specified blob or a file into an arraybuffer representing the input data as a binary string.
...And 5 more matches
WebGL2RenderingContext.fenceSync() - Web APIs
the webgl2renderingcontext.fencesync() method of the webgl 2 api creates a new webglsync object and inserts it into the gl command stream.
... syntax webglsync gl.fencesync(condition, flags); parameters condition a glenum specifying the condition that must be met to set the sync object's state to signaled.
... must be gl.sync_gpu_commands_complete.
...And 5 more matches
WebGL2RenderingContext.getSyncParameter() - Web APIs
the webgl2renderingcontext.getsyncparameter() method of the webgl 2 api returns parameter information of a webglsync object.
... syntax any gl.getsyncparameter(sync, pname); parameters sync a webglsync object.
...possible values: gl.object_type: returns a glenum indicating the type of the sync object (always gl.sync_fence).
...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
WebGL2RenderingContext.isSync() - Web APIs
the webgl2renderingcontext.issync() method of the webgl 2 api returns true if the passed object is a valid webglsync object.
... syntax glboolean gl.issync(sync); parameters sync a webglsync object to test.
... return value a glboolean indicating whether the given object is a valid webglsync object (true) or not (false).
...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
IDBTransactionSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the idbtransactionsync interface of the indexeddb api provides a synchronous transaction on a database.
... when an application creates an idbtransactionsync object, it blocks until the browser is able to reserve the require database objects.
...And 3 more matches
RTCRtpReceiver.getSynchronizationSources() - Web APIs
the getsynchronizationsources() method of the rtcrtpreceiver interface returns an array of rtcrtpcontributingsource instances, each corresponding to one ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... return value an array of rtcrtpsynchronizationsource instances.
... each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds.
...And 3 more matches
ServiceWorkerGlobalScope.onsync - Web APIs
the serviceworkerglobalscope.onsync event of the serviceworkerglobalscope interface is fired whenever a syncevent event occurs.
... this is triggered when a call to syncmanager.register is made from a service worker client page.
... the attempt to sync is made either immediately if the network is available or as soon as the network becomes available.
...And 3 more matches
WebGL2RenderingContext.deleteSync() - Web APIs
the webgl2renderingcontext.deletesync() method of the webgl 2 api deletes a given webglsync object.
... syntax void gl.deletesync(sync); parameters sync a webglsync object to delete.
...webglsync objects are not available in webgl 1.
...And 3 more matches
Syncing custom preferences - Archive of obsolete content
when preferences sync is enabled, firefox sync will synchronize preferences between the same application based on a whitelist.
... that means preferences between firefox and fennec, for instance, are never synced.
... to sync preferences between firefoxes, fennecs, thunderbirds, etc., ensure the prefs are whitelisted.
...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.
...And 2 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
FileEntrySync - Web APIs
the fileentrysync interface of the file system api represents a file in a file system.
... inherits from: entrysync about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011.
... method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents.
...And 2 more matches
IDBFactorySync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the idbfactorysync interface of the indexeddb api provide a synchronous means of accessing the capabilities of indexed databases.
... method overview idbdatabasesync open (in domstring name, in domstring description, in optional boolean modifydatabase) raises (idbdatabaseexception); methods open() opens and returns a connection to a database.
...And 2 more matches
SyncEvent - Web APIs
WebAPISyncEvent
the syncevent interface represents a sync action that is dispatched on the serviceworkerglobalscope of a serviceworker.
..." fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="191" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">extendableevent</text></a><polyline points="266,25 276,20 276,30 266,25" stroke="#d4dde4" fill="none"/><line x1="276" y1="25" x2="306" y2="25" stroke="#d4dde4"/><a xlink:href="/docs/web/api/syncevent" target="_top"><rect x="306" y="1" width="90" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="351" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">syncevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor syncevent.synceven...
...t() creates a new syncevent object.
...And 2 more matches
WebGL2RenderingContext.waitSync() - Web APIs
the webgl2renderingcontext.waitsync() method of the webgl 2 api returns immediately, but waits on the gl server until the given webglsync object is signaled.
... the method is a no-op in the absence of the possibility of synchronizing between multiple gl contexts.
... syntax void gl.waitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on.
...And 2 more matches
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.
XPCOM Thread Synchronization
xpcom thread synchronization primitives have the same semantics as those in nspr, and each method of these synchronization objects (e.g.
...this article covers the api of mozilla synchronization only.
... for a higher-level introduction to thread synchronization, see introduction_to_nspr.
...needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonitor); if (needexpensivecomputation()) { mutexautounlock au(mlock); } am.wait(); mcvar->notify(); } mozilla synchronization api reference the mozilla:: namespace exports the following synchronization primitives.
IDBCursorSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the idbcursorsync interface of the indexeddb api represents a cursor for iterating over multiple records in a database.
... you can have only one instance of idbcursorsync representing a cursor, but you can have an unlimited number of cursors at the same time.
...it enables an application to synchronously process all the records in the cursor's range.
IDBEnvironmentSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the unimplemented idbenvironmentsync interface of the indexeddb api will be implemented by worker objects.
... attributes attribute type description indexeddbsync readonly idbfactorysync provides a synchronous means of accessing the capabilities of indexed databases.
... note: until the indexed database api specification is finalized, this attribute should be accessed as moz_indexeddbsync.
RTCRtpSynchronizationSource - Web APIs
the rtcrtpsynchronizationsource dictionary of the the webrtc api is used by getsynchronizationsources() to describe a particular synchronization source (ssrc).
... a synchronization source is a single source that shares timing and sequence number space.
... since rtcrtpsynchronizationsource implements rtcrtpcontributingsource, its properties are also available.
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsynchronizationsource' in that specification.
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.
SyncEvent.lastChance - Web APIs
the syncevent.lastchance read-only property of the syncevent interface returns true if the user agent will not make further synchronization attempts after the current attempt.
... this is the value passed in the lastchance parameter of the syncevent() constructor.
... syntax var lastchance = syncevent.lastchance value a boolean that indicates whether the user agent will not make further synchronization attempts after the current attempt.
... specifications specification web background synchronization ...
SyncEvent.tag - Web APIs
WebAPISyncEventtag
the syncevent.tag read-only property of the syncevent interface returns the developer-defined identifier for this syncevent.
... this is the value passed in the tag parameter of the syncevent() constructor.
... syntax var tag = syncevent.tag value the developer-defined identifier for this syncevent.
... specifications specification status comment web background synchronizationthe definition of 'tag' in that specification.
SyncManager - Web APIs
the syncmanager interface of the the serviceworker api provides an interface for registering and listing sync registrations.
... methods syncmanager.register create a new sync registration and return a promise.
... syncmanager.gettags return a list of developer-defined identifiers for syncmanager registration.
... specifications specification status comment web background synchronizationthe definition of 'syncmanager' in that specification.
WebGLSync - Web APIs
WebAPIWebGLSync
the webglsync interface is part of the webgl 2 api and is used to synchronize activities between the gpu and the application.
... when working with webglsync objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.fencesync() webgl2renderingcontext.deletesync() webgl2renderingcontext.issync() webgl2renderingcontext.clientwaitsync() webgl2renderingcontext.waitsync() webgl2renderingcontext.getsyncparameter() examples creating a webglsync object in this example, gl must be a webgl2renderingcontext.
... webglsync objects are not available in webgl 1.
... var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); specifications specification status comment webgl 2.0the definition of 'webglsync' in that specification.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
synchronous refers to real-time communication where each party receives (and if necessary, processes and replies to) messages instantly (or as near to instantly as possible).
... many programming commands are also synchronous — for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to.
... learn more technical reference asynchronous synchronous and asynchronous requests using the xmlhttprequest() api ...
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 ...
PR_Sync
synchronizes any buffered data for a file descriptor to its backing device (disk).
... syntax #include <prio.h> prstatus pr_sync(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file.
... description pr_sync writes all the in-memory buffered data of the specified file to the disk.
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 ...
... 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().
nsISyncMessageSender
both sendsyncmessage() and sendrpcmessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a cpow request).
... methods jsval sendsyncmessage([optional] in astring messagename, [optional] in 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.
...sendrpcmessage() like sendsyncmessage(), except re-entrant.
FileReaderSync.readAsArrayBuffer() - Web APIs
the readasarraybuffer() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an arraybuffer.
... this interface is only available in workers as it enables synchronous i/o that could potentially block.
... specifications specification status comment file apithe definition of 'readasarraybuffersync' in that specification.
FileReaderSync.readAsBinaryString() - Web APIs
the readasbinarystring() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring.
... this interface is only available in workers as it enables synchronous i/o that could potentially block.
... specifications specification status comment file apithe definition of 'readasbinarystringsync' in that specification.
FileSystemSync - Web APIs
in the file system api, a filesystemsync object represents a file system.
... basic concepts the filesystemsync object is your gateway to the entire api and you will use it a lot.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetfilesystemsync non-standardchrome full support 13prefixed full support 13prefixed prefixed implemented with the vendor prefix: webkitedge full support ≤79prefixed full support ≤79prefixed prefixed implemented with the vendor pre...
ServiceWorkerRegistration.sync - Web APIs
the sync property of the serviceworkerregistration interface returns a reference to the syncmanager interface, which manages background synchronization processes.
... syntax var syncmanager = serviceworkerregistration.sync; value a syncmanager object.
... specifications specification status comment web background synchronization living standard initial definition.
SyncManager.getTags() - Web APIs
the syncmanager.gettags method of the syncmanager interface returns a list of developer-defined identifiers for syncmanager registrations.
... syntax syncmanager.gettags().then(function(tags[]) { ...
... }) returns a promise that resolves to an array of domstrings containing developer-defined identifiers for syncmanager registrations.
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'); ...
Feature-Policy: sync-xhr - HTTP
the http feature-policy header sync-xhr directive controls whether the current document is allowed to make synchronous xmlhttprequest requests.
... syntax feature-policy: sync-xhr <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin.
... default policy by default the policy is set to *, which means synchronous requests are allowed in all frames.
Rsyncing the CVS Repository - Archive of obsolete content
the mozilla.org cvs repository can be downloaded via rsync.
...here's how to do it: rsync -az --delete --stats cvs-mirror.mozilla.org::mozilla ~/cvs-mirror this will mirror the cvs repository into ~/cvs-mirror.
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.
FileReaderSync.readAsDataURL() - Web APIs
the readasdataurl() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring representing a data url.
... this interface is only available in workers as it enables synchronous i/o that could potentially block.
FileReaderSync.readAsText() - Web APIs
the readastext() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an domstring.
... this interface is only available in workers as it enables synchronous i/o that could potentially block.
IDBIndexSync - Web APIs
important: the synchronous version of the indexeddb api was originally intended for use only with web workers, and was eventually removed from the spec because its need was questionable.
... the idbindexsync interface of the indexeddb api provides synchronous access to an index in a database.
RTCRtpSynchronizationSource.voiceActivityFlag - Web APIs
the read-only voiceactivityflag property of the rtcrtpsynchronizationsource interface indicates whether or not the most recent rtp packet on the source includes voice activity.
... syntax var voiceactivity = rtcrtpsynchronizationsource.voiceactivityflag value a boolean value which is true if voice activity is present in the most recently received rtp packet played by the associated source, or false if voice activity is not present.
ServiceWorkerRegistration.periodicSync - Web APIs
the periodicsync read-only property of the serviceworkerregistration interface returns a reference to the periodicsyncmanager interface, which manages periodic background synchronization processes.
... syntax var periodicsyncmanager = serviceworkerregistration.periodicsync; value a periodicsyncmanager object.
syncSessions - Archive of obsolete content
« xul reference home syncsessions( autocompleteelement ) obsolete since gecko 26 return type: void copy the sessions from another autocomplete element.
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.
nsISyncJPAKE
services/crypto/component/nsisyncjpake.idlscriptable please add a summary to this article.
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.
...a timeline is a source of time values for synchronization purposes, and is an animationtimeline-based object.
... 81 animation.updateplaybackrate() api, animation, experimental, interface, method, reference, web animations, playbackrate, updateplaybackrate, waapi, web animations api the updateplaybackrate() method of the web animations api's animation interface sets the speed of an animation after first synchronizing its playback position.
...And 99 more matches
JavaScript Client API - Archive of obsolete content
overview this page describes how to use the internal client-side sync javascript api.
... this api is available in mozilla-based products that use sync, such as firefox desktop.
... the best, and most up-to-date, reference to sync's internal apis is the source code.
...And 48 more matches
Index
MozillaTechXPCOMIndex
94 xpcom thread synchronization thread_synchronization, threads, xpcom xpcom thread synchronization primitives have the same semantics as those in nspr, and each method of these synchronization objects (e.g.
... 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.
...And 33 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 32 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 27 more matches
TPS Tests
tps is an end to end test for sync.
... it's name stands for testing and profiling tool for sync (which is a misnomer, since it doesn't do any profiling), and it should not be confused with the similarly named tests in talos.
...the extension will read the test file and perform a series of actions specified therein, such as populating a set of bookmarks, syncing to the sync server, making bookmark modifications, etc.
...And 24 more matches
JavaScript Daemons Management - Archive of obsolete content
isfinite(this.length) && this.index < 1 : this.index + 1 > this.length; }; daemon.prototype.synchronize = function () { if (this.paused) { return; } clearinterval(this.session); this.session = setinterval(daemon.forcecall, this.rate, this); }; daemon.prototype.pause = function () { clearinterval(this.session); this.paused = true; }; /* system not required daemon instances methods */ /** * basic user interface.
... **/ daemon.prototype.start = function (breverse) { var bbackw = boolean(breverse); if (this.backw === bbackw && (this.isatend() || !this.paused)) { return false; } this.backw = bbackw; this.paused = false; if (this.onstart) { this.onstart.call(this.owner, this.index, this.length, this.backw); } this.synchronize(); return true; }; daemon.prototype.stop = function () { this.pause(); if (this.onstop) { this.onstop.call(this.owner, this.index, this.length, this.backw); } delete this.index; delete this.backw; delete this.reversals; }; /******************************* * daemon is now ready!
...-1 : 1; var bbreak = odmn.task.call(odmn.owner, odmn.index, odmn.length, odmn.backw) === false, bend = odmn.isatend(), binvert = odmn.reversals > 0; if (bend && !binvert || bbreak) { odmn.paused = true; return false; } if (bend && binvert) { odmn.backw = !odmn.backw; odmn.reversals--; } odmn.synchronize(); return true; }; /* system not required daemon.safe global object methods */ /** * daemon.safe global object optional methods (shortcuts).
...And 23 more matches
Performance best practices for Firefox front-end engineers
see detecting and avoiding synchronous reflow below for more information.
... detecting and avoiding synchronous style flushes what are style flushes?
... however, it's possible for script to do things that force multiple style calculations (or style flushes) to occur synchronously during the javascript part of the 16 ms window.
...And 23 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 autf8stri...
... note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads.
...And 19 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!
... 472 firefox sync sync sync refers to a family of related components and services which provide synchronization of data between mozilla application instances.
...And 18 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
Storage
closing a connection to close a connection on which only synchronous transactions were performed, use the mozistorageconnection.close() method.
... if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose() method.
... binding one set of parameters if you only have one row to insert, or are using the synchronous api you'll need to use this method.
...And 15 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.
... the synchronous api, on the other hand, allows for simpler programming model, but it must be used with webworkers.
...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
File and Directory Entries API - Web APIs
two very similar apis exist depending on whether you desire asynchronous or synchronous behavior.
... the synchronous api is intended to be used inside a worker and will return the values you desire.
... 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.
...And 13 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 13 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 13 more matches
AddonManager
the majority of the methods are asynchronous meaning that results are delivered through callbacks passed to the method.
...getaddonbysyncguid(in string id, in addoncallback?
... 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...
...And 12 more matches
Audio for Web games - Game development
using the playbackrate() method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action.
...this is often the way that musicians compose music anyway, and the web audio api is extremely good at keeping these parts in sync.
... loading your tracks with the web audio api you can load separate tracks and loops individually using xmlhttprequest or the fetch api, which means you can load them synchronously or in parallel.
...And 11 more matches
Code snippets - Archive of obsolete content
this page documents how to perform custom actions with firefox sync via javascript.
...components.utils.import("resource://services-sync/main.js"); // obtain a reference to the main firefox window.
...terfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); // obtain a reference to sync's tabs "engine." let tabsengine = weave.service.enginemanager.get("tabs"); // iterate over each client having data.
...And 10 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
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.
... where absolutely necessary, frame scripts can pass wrappers called cross process object wrappers (also known as cpows) to chrome, and chrome can use these wrappers to get synchronous access to content objects.
... content to chrome the frame script can choose to send synchronous or asynchronous messages to chrome code.
...And 10 more matches
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.
...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 - Learn web development
beginner, ftp, github, uploading, webmechanics, hosting, rsync, sftp if you have built a simple web page (see html basics for an example), you will probably want to put it online, on a web server.
... in this article we'll discuss how to do that, using various available options such as sftp clients, rsync and github.
... 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.
...And 9 more matches
Cross Process Object Wrappers
this document describes cross process object wrappers (cpows), which enable chrome code to synchronously access content in multiprocess firefox.
... chrome to content messaging must be asynchronous.
... converting synchronous code to be asynchronous can be difficult and time-consuming.
...And 9 more matches
IME handling guide
finally, this class guarantees that requesting to commit or cancel current composition to ime is perefored synchronously.
...unfortunately, it's not allowed to use syncronous communication from chrome process to a remote process.
... notify_ime_of_blur when an imecontentobserver instance ends observing the focused editor, this is sent to widget synchronously because assumed that this notification causes neither query content events nor composition events.
...And 9 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
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 8 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...
...proxy auto config (pac) may perform a synchronous dns query, which may not return immediately.
... by passing this flag to resolve, one can failover to asyncresolve to avoid locking up the calling thread if a pac query is required.
...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
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 7 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
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 7 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 7 more matches
WebGL best practices - Web APIs
for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well.
...geterror, getparameter) certain webgl entry points cause synchronous stalls on the calling thread.
...(this is okay for read buffers in conjunction with fences - see async data readback below.) readpixels() to the cpu (i.e.
...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
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 6 more matches
How do you upload your files to a web server? - Learn web development
in this article we'll discuss how to do that, using various available options such as sftp clients, rsync and github.
... rsync rsync is a local-to-remote file synchronizing tool, which is generally available on most unix-based systems (like macos and linux), but windows versions exist too.
...a basic command looks like so: rsync [-options] source user@x.x.x.x:destination -options is a dash followed by a one or more letters, for example -v for verbose error messages, and -b to make backups.
...And 6 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 6 more matches
Sqlite.jsm
all operations are asynchronous.
... use of synchronous storage apis is discouraged because they block the main thread.
... all the functionality in sqlite.jsm is asynchronous.
...And 6 more matches
Scroll-linked effects
these effects work well in browsers where the scrolling is done synchronously on the browser's main thread.
... 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.
...And 6 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 6 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 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
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!
... // you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read with content type hint it's useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous i/o).
...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
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 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 attri...
... 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
L20n Javascript API
you can listen to the ready event (emitted by the context instance when all the resources have been compiled) and use ctx.getsync and ctx.getentitysync to get translations synchronously.
...d, 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.
...And 5 more matches
Introduction to NSPR
the netscape portable runtime (nspr) api allows compliant applications to use system facilities such as threads, thread synchronization, i/o, interval timing, atomic operations, and several other low-level services in a platform-independent manner.
...nspr provides a function, pr_cleanup, that synchronizes process termination.
...this preference is still subject to resource availability, and must not be used in place of proper synchronization.
...And 5 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 5 more matches
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.
...by logging reflow events the web console can give you insight into when reflow events are being triggered, how long they take to execute and, if the reflows are synchronous reflows triggered from javascript, which code triggered them.
...And 5 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 5 more matches
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.beginquery() begins an asynchronous query.
... webgl2renderingcontext.endquery() marks the end of an asynchronous query.
... sync objects webgl2renderingcontext.fencesync() creates a new webglsync object and inserts it into the gl command stream.
...And 5 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.
...for example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and indexed db, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) the api is used as follows: the lock is requested.
... work is done while holding the lock in an asynchronous task.
...And 5 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
Adding a new todo form: Vue events, methods, and models - Learn web development
v-model binds to the data property you set on it and keeps it in sync with the <input>.
...do this now: <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" v-model="label" /> note: you can also sync data with <input> values through a combination of events and v-bind attributes.
...this modifier changes when v-model syncs the value for text inputs.
...And 4 more matches
HTML parser threading
(again, here we get to move a bunch of tree ops by obtaining a mutex once instead of having to synchronize thread on a per-tree op basis.) if the executor isn't reading from a stage, it calls nshtml5parser::parseuntilblocked() to parse potential document.write()-generated data into tree ops.
...(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.
...And 4 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 4 more matches
nsIChannelEventSink
note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method.
... 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.
...And 4 more matches
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_sync acts just like a function call in that it blocks the calling thread until the the method is invoked on the destination thread.
...And 4 more matches
Basic concepts - Web APIs
indexeddb is an asynchronous api that can be used in most contexts, including web workers.
... it used to include a synchronous version also, for use in web workers, but this was removed from the spec due to lack of interest by the web community.
... the indexeddb api is mostly asynchronous.
...And 4 more matches
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.
... historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers.
...And 4 more matches
HTML in XMLHttpRequest - Web APIs
limitations to discourage the synchronous use of xmlhttprequest, html support is not available in the synchronous mode.
... usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but before calling send().
... 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.
...And 4 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 4 more matches
Web APIs
WebAPI
pointreadonly domquad domrect domrectreadonly domstring domstringlist domstringmap domtimestamp domtokenlist domuserdata datatransfer datatransferitem datatransferitemlist dedicatedworkerglobalscope delaynode deprecationreportbody devicelightevent devicemotionevent devicemotioneventacceleration devicemotioneventrotationrate deviceorientationevent deviceproximityevent directoryentrysync directoryreadersync displaymediastreamconstraints document documentfragment documentorshadowroot documenttimeline documenttouch documenttype doublerange dragevent dynamicscompressornode e ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression...
..._rgtc ext_texture_filter_anisotropic eckeygenparams eckeyimportparams ecdhkeyderiveparams ecdsaparams effecttiming element elementcssinlinestyle elementtraversal errorevent event eventlistener eventsource eventtarget extendableevent extendablemessageevent f featurepolicy federatedcredential fetchevent file fileentrysync fileerror fileexception filelist filereader filereadersync filerequest filesystem filesystemdirectoryentry filesystemdirectoryreader filesystementry filesystementrysync filesystemfileentry filesystemflags filesystemsync focusevent fontface fontfaceset fontfacesetloadevent formdata formdataentryvalue formdataevent fullscreenoptions g gainnode gamepad gamepadbutton gamepadevent gamepadhapticactuator geolocation geolocationcoordinates geol...
...lspanelement htmlstyleelement htmltablecaptionelement htmltablecellelement htmltablecolelement htmltableelement htmltablerowelement htmltablesectionelement htmltemplateelement htmltextareaelement htmltimeelement htmltitleelement htmltrackelement htmlulistelement htmlunknownelement htmlvideoelement hashchangeevent headers history hkdfparams hmacimportparams hmackeygenparams i idbcursor idbcursorsync idbcursorwithvalue idbdatabase idbdatabaseexception idbdatabasesync idbenvironment idbenvironmentsync idbfactory idbfactorysync idbindex idbindexsync idbkeyrange idblocaleawarekeyrange idbmutablefile idbobjectstore idbobjectstoresync idbopendbrequest idbrequest idbtransaction idbtransactionsync idbversionchangeevent idbversionchangerequest iirfilternode idledeadl...
...And 4 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 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
begin - SVG: Scalable Vector Graphics
WebSVGAttributebegin
each individual value can be one of the following : <offset-value>, <syncbase-value>, <event-value>, <repeat-value>, <accesskey-value>, <wallclock-sync-value> or the keyword indefinite.
... <syncbase-value> this value defines a syncbase and an optional offset from that syncbase.
... a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the beginning or active end of the referenced animation element.
...And 4 more matches
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.
... never use synchronous xmlhttprequests.
... netutils.jsm provides helpers for asynchronous reading and copying of files.
...And 3 more matches
Anatomy of a video game - Game development
calling the next requestanimationframe early ensures the browser receives it on time to plan accordingly even if your current frame misses its vsync window.
...because main() is called once in the second statement and every call of it places itself in the queue of things to do next frame, main() is synchronized to your framerate.
... sleep (unless an event interrupts the browser's nap) until the monitor is ready for your image (vsync) and repeat.
...And 3 more matches
Efficient animation for web games - Game development
though javascript animations can be easier to express at times, unless you have a great need to synchronise ui animation state with game animation state, you’re unlikely to be able to do a better job than the browser.
...there are signals at the beginning and end of animations that allow you to attach javascript callbacks and form a rudimentary form of synchronisation (though there are no guarantees on how promptly these callbacks will happen).
... use requestanimationframe when you are animating <canvas> content, or when your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout.
...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
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
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.
...nspr's file i/o is done using windows 3.1's synchronous file i/o api.
...And 3 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 a synchronous transfer on a channel, you are handed back a stream that you can read or write from or to.
...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
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.
... this is also a synchronous (blocking) operation, so if you're in javascript, consider using netutil.jsm as described below.
... 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).
...And 3 more matches
mozIStorageStatement
ndint32parameter(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
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.
... getcachedbydomainandname() synchronously retrieves from the in-memory cache the preference with the given domain and name.
...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
nsIStreamConverter
stream converter users there are currently two ways to use a stream converter: synchronous: stream to stream.
... 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, ...
...And 3 more matches
nsIZipWriter
attempting to perform a synchronous operation on the interface while the background queue is in progress will throw an ns_error_in_progress exception.
...if the operation is performed on the queue then the channel will be opened asynchronously, otherwise the channel must support being opened synchronously.
...(a forward slash is '/') detail: this azipentry is very important, this example demonstrates its usage: var zw = cc['@mozilla.org/zipwriter;1'].createinstance(ci.nsizipwriter); var myzipfile = fu.file('c:\\myzipfile.zip'); //this file will be creatd in c drive var pr = {pr_rdonly: 0x01, pr_wronly: 0x02, pr_rdwr: 0x04, pr_create_file: 0x08, pr_append: 0x10, pr_truncate: 0x20, pr_sync: 0x40, pr_excl: 0x80}; zw.open(xpi, pr.pr_wronly | pr.pr_create_file | pr.pr_truncate); //xpi file is created if not there, if it is there it is truncated/deleted var filetoaddtozip = fileutils.file('c:\\add this file.txt'); var saveinzipas = 'blah.txt'; zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); in the above example, the file ("add this file.txt") l...
...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
Service Worker API - Web APIs
they will also allow access to push notifications and background sync 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.
... other use case ideas service workers are also intended to be used for such things as: background data synchronization.
...And 3 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 3 more matches
Appendix D: Loading Scripts - Archive of obsolete content
these tags are generally inserted into xul overlay files or other xul documents, after which they are automatically loaded into the context of the xul window in question and executed immediately and synchronously.
... in addition to compile time, reading files synchronously from disk has its own overhead, and xmlhttprequests have significantly more overhead than native loading methods.
... advantages asynchronous: workers execute asynchronously in their own threads, which means that they have limited risk of interfering with the main thread.
...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.
...And 2 more matches
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.
...And 2 more matches
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.
...And 2 more matches
About NSPR
these facilities include threads, thread synchronization, normal file and network i/o, interval timing and calendar time, basic memory management (malloc and free) and shared library linking.
... thread synchronization thread synchronization is loosely based on monitors as described by c.a.r.
...additionally, nspr provides synchronization methods more suited for use by java.
...And 2 more matches
History Service Design
temporary storage is used to avoid too frequent writes to the disk, since those are most likely to cause fsyncs (to ensure data integrity) on the target filesystem.
... the temporary data (actually visits and pages) are synced to disk either on a timer and on bookmark's inserts.
...the internal syncing service takes care of initializing places, syncing data to disk and finalize statements, so usually that's not a problem.
...And 2 more matches
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.
...And 2 more matches
nsIMessageListener
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used to receive messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces.
...this function receives a message from one of the three message-sending functions in the message manager framework: broadcastasyncmessage sendasyncmessage sendsyncmessage.
... sync true if the message was sent using sendsyncmessage, false otherwise.
...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
= 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
nsIRequest
this will close any open input or output streams and terminate any async requests.
... implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function.
... similarly, removal from the load group (if any) must also happen asynchronously.
...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
Performance
when transactions are committed, sqlite does journaling which requires syncing data to disk.
...the asynchronous writes discussed below removes most of the immediate penalty of a commit, so you will not notice the problem as much.
...for each commit, sqlite does two disk syncs among many other file operations (see the "atomic commit" section of http://www.sqlite.org/php2004/slides-all.html for more information on how this works).
...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 retrieve...
... 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.createel...
...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 retrieve...
... 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.createel...
...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
XMLHttpRequest.responseType - Web APIs
exceptions invalidaccesserror an attempt was made to change the value of responsetype on anxmlhttprequest which is in synchronous mode but not in a worker.
... for additional details, see synchronous xhr restrictions below.
... usage notes synchronous xhr restrictions you cannot change the value of responsetype in a synchronous xmlhttprequest except when the request belongs to a worker.
...And 2 more matches
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.
...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
Binding Attachment and Detachment - Archive of obsolete content
var checkbox = document.getelementbyid("mycheckbox"); checkbox.style.mozbinding = "url(http://www.mozilla.org/xbl/htmlbindings.xml#checkbox)"; this attachment is not necessarily synchronous.
...therefore if all the bindings in a chain come from binding documents that have already been loaded by the bound document, then the attachment of a binding (either through css or through the dom) is guaranteed to be synchronous.
... an author can ensure that all bindings are synchronously attached by calling loadbindingdocument to pre-fetch any xbl documents that are required.
... if the binding document is loaded prior to the firing of the load event, then any binding attachments that are placed following the load will be synchronous if they come from one of these previously loaded binding documents.
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.
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
the framework updates this virtual representation which is then synced with the "real" dom.
... 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.
Application cache implementation overview
it synchronously returns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace.
...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.
How to implement a custom autocomplete search component
results[index]; }, 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 = ['mar...
...y', 'john']; var autocomplete_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.
...ice(index, 1); }, 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 ...
...ush(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...
Profiling with the Firefox Profiler
note that high priority events such as vsync are not included here.
... black: these indicate synchronous ipc calls.
...for example:in the results above we can see that we're spending ~287 milliseconds in startup::xre_initchildprocess, 194 ms of which are spent in pvsync::msg_notify and all child functions that it calls.
... synchronous re-flow can be caused by js that, for example, makes changes to the page content in a loop and queries about the layout of the page in that same loop.
Rhino shell
sync(function) creates a synchronized function (in the sense of a java synchronized method) from an existing function.
... the new function synchronizes on the this object of its invocation.
... $ java org.mozilla.javascript.tools.shell.main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.main js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test.
... js> function test(x) { print("entry"); java.lang.thread.sleep(x*1000); print("exit"); } js> var o = { f : sync(test) }; js> spawn(function() {o.f(5);}); thread[thread-0,5,main] entry js> spawn(function() {o.f(5);}); thread[thread-1,5,main] js> exit entry exit runcommand here are a few examples of invoking runcommand under linux.
Mozilla Projects
firefox sync firefox sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices.
...unlike other tools, it understands compiler-builtin atomics and synchronization and therefore provides very accurate results with no real false positives.
... tps tests tps is an end to end test for sync.
... it's name stands for testing and profiling tool for sync (which is a misnomer, since it doesn't do any profiling), and it should not be confused with the similarly named tests in talos.
Making cross-thread calls using runnables
in general, threading and message passing should be asynchronous.
... for example, let's say we have a function, calculatepi(int digits), which will calculate π to an arbitrary number of digits: void calculatepi(int digits, nscstring& result); // this is synchronous this can take a while, so we don't want to run this on the main thread.
...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(...
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 ...
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.
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.
... see also content process event handling nsiframemessagelistener nsisyncmessagesender ...
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.
nsITextInputProcessorNotification
when this is requested, the callback should commit composition synchronously, i.e., nsitextinputprocessor.commitcomposition() should be called.
... if the callback doesn't want to commit the composition synchronously, it's okay to commit it later (i.e., asynchronously).
... when this is requested, the callback should cancel composition synchronously, i.e., nsitextinputprocessor.cancelcomposition() should be called.
... if the callback doesn't want to cancel the composition synchronously, it's okay to cancel it later (i.e., asynchronously).
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.
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.
... to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data.
... the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower.
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...
HTMLImageElement.decoding - Web APIs
possible values are: sync: decode the image synchronously for atomic presentation with other content.
... 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.
... examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
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.
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 => { // brows...
... requestorresponse.addeventlistener(event, async function listener(ev) { const promisetovalidate = validator(requestorresponse); ev.updatewith(promisetovalidate); const errors = await promisetovalidate; if (!errors) { // yay!
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.
... sync triggered when a call to syncmanager.register is made from a service worker client page.
... the attempt to sync is made either immediately if the network is available or as soon as the network becomes available.
... also available via the serviceworkerglobalscope.onsync property.
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.
Migrating from webkitAudioContext - Web APIs
ow: var osc = context.createoscillator(); osc.noteon(1); osc.noteoff(1.5); var src = context.createbuffersource(); src.notegrainon(1, 0.25); src.noteoff(2); you can simply change it like this in order to port it to the standard audiocontext api: var osc = context.createoscillator(); osc.start(1); osc.stop(1.5); var src = context.createbuffersource(); src.start(1, 0.25); src.stop(2); remove synchronous buffer creation in the old webkit implementation of web audio, there were two versions of createbuffer(), one which created an initially empty buffer, and one which took an existing arraybuffer containing encoded audio, decoded it and returned the result in the form of an audiobuffer.
... the latter version of createbuffer() was potentially expensive, because it had to decode the audio buffer synchronously, and with the buffer being arbitrarily large, it could take a lot of time for this method to complete its work, and no other part of your web page's code could execute in the mean time.
... because of these problems, this version of the createbuffer() method has been removed, and you should use the asynchronous decodeaudiodata() method instead.
...t(); 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.
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.
... note: synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous xhr support on the main thread entirely.
... synchronous requests are permitted in workers.
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!
WebAssembly.Module() constructor - JavaScript
the webassembly.module() constructor function can be called to synchronously compile given webassembly binary code.
... 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.
... examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
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.
end - SVG: Scalable Vector Graphics
WebSVGAttributeend
<syncbase-value> this value defines a syncbase and an optional offset from that syncbase.
... a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the beginning or active end of the referenced animation element.
... <wallclock-sync-value> this value defines the animation end time as a real-world clock time.
... a valid wallclock-sync-value consists of the function wallclock() with a time value as parameter.
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.
... callmessage(amessagename [, v1 [, v2 [, ...]]]) this function is like sendmessage() but sends the message synchronously.
...gc() synchronously performs garbage collection.
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.
Index of archived content - Archive of obsolete content
ding a handler documentation for bidi mozilla downloading nightly or trunk builds jss build instructions for osx 10.6 layout faq layout system overview multiple firefox profiles repackaging firefox style system overview using microformats firefox sync code snippets javascript client api syncing custom preferences force rtl gre gre registration gecko coding help wanted http class overview hacking wiki help viewer creating ...
...ild bundlelibrary bundles configuration extensions faq hostwindow installer scripting styling proxy ui pydom rdf api rdf datasource how-to reading textual data remote xul remote debugging rsyncing the cvs repository running windows debug builds downloaded from tinderbox sxsw 2007 presentations safe browsing safe browsing: design documentation safely loading uris same origin policy for xbl space manager detailed design space manager high level design standalone xpcom standard makefile head...
... 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...
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
n(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...
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.
...y, and much of the dom; mathml rendering; an ecma-262 edition 3-compliant javascript engine; java integration with a bridge to xpcom, a java dom api, the open jvm integration (oji) facility, a java webclient api, and java plug-ins; nspr, a runtime engine that provides platform-independence (across over a dozen platforms) for non-gui operating system facilities with support for threads, thread synchronization, normal file and network i/o, interval timing and calendar time, basic memory management (malloc and free) and shared library linking; psm, a set of libraries that perform cryptographic operations including setting up an ssl connection, object signing and signature verification, certificate management (including issuance and revocation), other common pki functions, and s/mime support;...
Porting NSPR to Unix Platforms - Archive of obsolete content
on other platforms, you may need to do extra work to deal with their idiosyncrasies.
...pthreads nspr has relatively orthogonal source code in the thread management, thread synchronization, and i/o area.
...for thread management and synchronization: <tt>cvar -d</tt> <tt>cvar2</tt> <tt>./join -d</tt> <tt>perf</tt> <tt>./switch -d</tt> <tt>intrupt -d</tt> for i/o: <tt>cltsrv -d</tt>, <tt>cltsrv -gd</tt> <tt>socket</tt> <tt>testfile -d</tt> <tt>tmocon -d</tt> '<tt>tmoacc -d</tt>' in conjunction with '<tt>writev -d</tt>' miscellaneous: <tt>dlltest -d</tt> <tt>forktest</tt> original document information author: ...
XUL Events - Archive of obsolete content
attribute: onpopupshown syncfrompreference this event is sent when the element is being changed because a preference changed, or when an element is initialized from a preference.
... attribute: onsyncfrompreference synctopreference this event is sent when the element connected to a preference has changed.
... attribute: onsynctopreference underflow this event is sent to an element when there becomes enough space to display it at full size.
preference - Archive of obsolete content
in pref dialogs with instantapply == true (default on mac os x) this value is kept in sync with the actual value stored in the preferences (see valuefrompreferences).
...this function calls onsynctopreference.
...this function calls onsyncfrompreference.
Using IO Timeout And Interrupt On NT - Archive of obsolete content
nspr io on nt the io model of nspr 2.0 is synchronous and blocking.
...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.
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).
... 26 audio for web games audio, games, web audio api, audio sprites, spatialization, syncing tracks audio is an important part of any game; it adds feedback and atmosphere.
TCP handshake - MDN Web Docs Glossary: Definitions of Web-related terms
the three messages transmitted by tcp to negotiate and start a tcp session are nicknamed syn, syn-ack, and ack for synchronize, synchronize-acknowledgement, and acknowledge respectively.
... the host, generally the browser, sends a tcp synchronize packet to the server.
... the server receives the syn and sends back a synchronize-acknowledgement.
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.
Web performance resources - Learn web development
as we learned in the critical rendering path document, linking css with a tradional link tag with rel="stylesheet" is synchronous and blocks rendering.
... 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.
React interactivity: Events and state - Learn web development
this means that the browser and our app are now out-of-sync.
... we have to write our own code to put the browser back in sync with our app.
... synchronizing the browser with our data let’s revisit our toggletaskcompleted() function in app.js.
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.
Creating Sandboxed HTTP Connections
o-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.
...nts.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...
Gecko Logging
sync print each log synchronously, this is useful to check behavior in real time or get logs immediately before crash.
... for example, if you want to specify "sync", "timestamp" and "rotate": set moz_log="example_logger:3,timestamp,sync,rotate:10" to adjust the logging after firefox has started, you can set prefs under the logging.
...the special boolean prefs logging.config.sync and logging.config.add_timestamp can be used to control the sync and timestamp properties described above.
Limitations of chrome scripts
for example: whenever extensions try to access web content from the chrome process, the browser will return a cross process object wrapper that gives the chrome code synchronous access to the content.
... limitations of cpows cross process object wrappers (cpows) are a migration aid giving chrome code synchronous access to content objects.
...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 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.
MozBeforePaint
gecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.
... the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions.
... this allows multiple animations to remain in sync with one another within the context of a given window.
Addon
syncguid read only string string guid to identify the add-on in sync.
... the guid is generated randomly and is made consistent across devices during sync.
...this will perform asynchronously and deliver results to the given listener.
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.
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.
... os.file for workers synchronous file i/o for worker threads os.file.directoryiterator for workers visiting directories synchronously from a worker thread ...
Nonblocking IO In NSPR
introduction previously, all i/o in the netscape portable runtime (nspr) was blocking (or synchronous).
...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.
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 c...
...omplete) 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.
Places Developer Guide
this is mainly for use by extensions that sync bookmark data between different profiles.
...this is mainly for use by extensions that sync bookmark data between different profiles.
...: 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.
Using the Places history service
nsiautocompletesearch: url-bar autocomplete from history from 1.9.1 (firefox3.1) on, don't use any places service on (or after) quit-application has been notified, since the database connection will be closed to allow the last sync, and changes will most likely be lost.
...it is designed for people writing synchronizing or backup services that need access to all the flags.
...it is designed for synchronizing or backup services.
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.
...if you are referencing instances of mozistoragestatement referencing places databases when this notification occurs, you should call their mozistoragestatement.finalize() method places-sync-finished sent when the places database has been successfully flushed to disk.
imgIDecoderObserver
decode notifications may or may not be synchronous, depending on the situation.
... if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call returns.
... if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns.
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.
nsIFrameMessageListener
sync a boolean value indicating whether or not the message should be handled synchronously.
... json the json object in which to return the response if the message is being handled synchronously.
... objects unimplemented an array of cpow, or null if sync is false.
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.
...if the message was sent synchronously from the jetpack process via callmessage(), then the return value of this function is passed back to the jetpack process.
... evalscript() this asynchronously sends code to the jetpack process for evaluation.
nsIMsgDatabase
nsisimpleenumerator enumeratemessages(); nsisimpleenumerator enumeratethreads(); void synccounts; nsimsgthread getthreadcontainingmsghdr(in nsimsgdbhdr msghdr); void markhdrread(in nsimsgdbhdr msghdr, in boolean bread, in nsidbchangelistener instigator); void markhdrreplied(in nsimsgdbhdr msghdr, in boolean breplied, in nsidbchangelistener instigator); void markhdrmarked(in nsimsgdbhdr msghdr, in boolean mark,in nsidbchangelistener instigator); void markmdnneeded(in nsmsgkey ...
...b() void addnewhdrtodb(in nsimsgdbhdr newhdr, in boolean notify); copyhdrfromexistinghdr() nsimsgdbhdr copyhdrfromexistinghdr(in nsmsgkey key, in nsimsgdbhdr existinghdr, in boolean addhdrtodb); listallkeys() [noscript] void listallkeys(in nsmsgkeyarrayref outputkeys); enumeratemessages() nsisimpleenumerator enumeratemessages(); enumeratethreads() nsisimpleenumerator enumeratethreads(); synccounts() count the total and unread msgs, and adjust global count if needed.
... void synccounts(); getthreadcontainingmsghdr() nsimsgthread getthreadcontainingmsghdr(in nsimsgdbhdr msghdr) ; markhdrread() helpers for user command functions like delete, mark read, etc.
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.
nsISHEntry
void syncpresentationstate(); attributes attribute type description cachekey nsisupports set and get the cache key for the entry.
...void seturi( in nsiuri auri ); parameters auri native code only!setviewerbounds void setviewerbounds( in nsintrect bounds ); parameters bounds syncpresentationstate() ensure that the cached presentation members are self-consistent.
...void syncpresentationstate(); parameters none.
nsISelection2
void scrollintoview(in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent); attributes attribute type description type short returns the type of the selection (see nsiselectioncontroller for available constants).
... void scrollintoview( in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent ); parameters aregion the region inside the selection to scroll into view (see selection region constants defined in nsiselectioncontroller).
... aissynchronous when true, scrolls the selection into view before returning.
nsISelectionPrivate
obsolete since gecko 12.0 long gettableselectiontype(in nsidomrange range); void removeselectionlistener(in nsiselectionlistener listenertoremove); void scrollintoview(in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent); void setancestorlimiter(in nsicontent acontent); native code only!
... void scrollintoview( in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent ); parameters aregion the region inside the selection to scroll into view (see selection region constants defined in nsiselectioncontroller).
... aissynchronous when true, scrolls the selection into view before returning.
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.
...sslistener", "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 = docshel...
nsIXPConnect
pcfunctionthistranslator setfunctionthistranslator(in nsiidref aiid, in nsixpcfunctionthistranslator atranslator); void setreportalljsexceptions(in boolean reportalljsexceptions); void setsafejscontextforcurrentthread(in jscontextptr cx); void setsecuritymanagerforjscontext(in jscontextptr ajscontext, in nsixpcsecuritymanager amanager, in pruint16 flags); void syncjscontexts(); void updatexows(in jscontextptr ajscontext, in nsixpconnectwrappednative aobject, in pruint32 away); native code only!
...ion exceptions thrown missing exception missing description setsecuritymanagerforjscontext() void setsecuritymanagerforjscontext( in jscontextptr ajscontext, in nsixpcsecuritymanager amanager, in pruint16 flags ); parameters ajscontext missing description amanager missing description flags missing description exceptions thrown missing exception missing description syncjscontexts() deprecated do-nothing function.
... void syncjscontexts(); parameters none.
nsIXmlRpcClient
o 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.
XPCOM Interface Reference
accessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstallcallbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletioncallbackmozistorageconnectionmozistorageerrormozistoragefunctionmozistoragependingstatem...
...tnsiaccessibletextnsiaccessibletextchangeeventnsiaccessibletreecachensiaccessiblevaluensiaccessiblewin32objectnsialertsservicensiannotationobservernsiannotationservicensiappshellnsiappshellservicensiappstartupnsiappstartup_mozilla_2_0nsiapplicationcachensiapplicationcachechannelnsiapplicationcachecontainernsiapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirectcallbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthpromptcallbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertlistener2n...
...isupports proxiesnsisupportsarraynsisupportscstringnsisupportscharnsisupportsdoublensisupportsfloatnsisupportsidnsisupportsinterfacepointernsisupportsprboolnsisupportsprint16nsisupportsprint32nsisupportsprint64nsisupportsprtimensisupportspruint8nsisupportspruint16nsisupportspruint32nsisupportspruint64nsisupportsprimitivensisupportsprioritynsisupportsstringnsisupportsvoidnsisupportsweakreferencensisyncjpakensisyncmessagesendernsitxttohtmlconvnsitaggingservicensitaskbarpreviewnsitaskbarpreviewbuttonnsitaskbarpreviewcontrollernsitaskbarprogressnsitaskbartabpreviewnsitaskbarwindowpreviewnsitelemetrynsitextinputprocessornsitextinputprocessorcallbacknsitextinputprocessornotificationnsithreadnsithreadeventfilternsithreadinternalnsithreadmanagernsithreadobservernsithreadpoolnsithreadpoollistenernsitim...
XPCOM Interface Reference by grouping
iaccessibleeditabletext nsiaccessibleevent nsiaccessiblehyperlink nsiaccessiblehypertext nsiaccessibleimage nsiaccessibleprovider nsiaccessibleretrieval nsiaccessiblerole nsiaccessiblescrolltype nsiaccessibleselectable nsiaccessiblestates nsiaccessibletable nsiaccessibletext nsiaccessibletreecache nsiaccessiblevalue nsiaccessnode nsisyncmessagesender script nsiscriptableunescapehtml nsiscriptableunicodeconverter nsiscripterror nsiscripterror2 stylesheet nsistylesheetservice url nsiuri nsiurl util nsidomserializer nsidomxpathevaluator nsidomxpathexception nsidomxpathexpression nsidomxpathresult xslt nsixsltexception nsixsltprocessor ...
...reference 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 ...
MailNews Filters
in the case of pop3, filter execution is synchronous.
... for each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header.
... for imap, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't run until we've finished downloading headers.
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.
Drawing and Event Handling - Plugins
if a plug-in calls one of these methods, it receives a paint message asynchronously.
...a plug-in can call npn_forceredraw() to force a paint message synchronously, once an area has been invalidated with npn_invalidaterect() or npn_invalidateregion().
... void npn_forceredraw(npp instance); this method results in a synchronous update event or paint message for the plug-in.
Work with animations - Firefox Developer Tools
this article covers three tools you can use to visualize and edit animations: the animation inspector editing @keyframes editing timing functions animation inspector the page inspector's animations view displays animations in the page synchronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point.
... right-click in the box and select "inspect element" make sure the selected element is the <div class="channel"> switch over to the "animations" tab play the animation let's take a closer look at the contents of the animation inspector here: it shows a synchronized timeline for every animation applied to the selected element or its children.
...it doesn't make much sense to try to animate a geometric property and a translation at the same time — the two effects won't be synchronized — so the transform property is deliberately not handed over to the compositor to handle.
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.
Document: DOMContentLoaded event - Web APIs
synchronous javascript pauses parsing of the dom.
... 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.
... examples basic usage document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); delaying domcontentloaded <script> document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // this synchronous script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later.
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.
File and Directory Entries API support in Firefox - Web APIs
chrome deviations from the specification the largest compatibility issue still remaining is that chrome is still using older names for many of the interfaces in the api, since they implemented a related but different specification: name in specification name in google chrome filesystemdirectoryentry directoryentry filesystemdirectoryentrysync directoryentrysync filesystemdirectoryreader directoryreader filesystemdirectoryreadersync directoryreadersync filesystementry entry filesystementrysync entrysync filesystemfileentry fileentry filesystemfileentrysync fileentrysync be sure to account for this in your code by allowing for both names.
... only the asynchronous versions of the interfaces are implemented.
... any interfaces with names that end in "sync" aren't available.
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.addTrack() - Web APIs
instead, the streams are simply a way to group tracks together on the receiving end of the connection, making sure they are synchronized.
... 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.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().
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
together, these two objects provide statistics about the inbound and outbound sides of the same synchronization source (ssrc).
... 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...
SVGImageElement.decoding - Web APIs
possible values are: sync: decode the image synchronously for atomic presentation with other content.
... async: decode the image asynchronously to reduce delay in presenting other content.
... examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.svg'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
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.
... if you app is synchronizing data from a remote server, consider using background sync.
ServiceWorkerRegistration - Web APIs
serviceworkerregistration.sync read only returns a reference to the syncmanager interface, which manages background synchronization processes.
... unimplemented properties serviceworkerregistration.periodicsync read only returns a reference to the periodicsyncmanager interface, which manages periodic background synchronization processes.
... web background synchronization living standard adds the sync property.
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.
... 46 (46) no support (yes) no support filereadersync this api allows synchronous read of blob and file objects.
... (yes) (yes) (yes) (yes) promise javascript objects that allow you to write asynchronous functions.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
isfinite(this.length) && this.index < 1 : this.index + 1 > this.length; }; minidaemon.prototype.synchronize = function () { if (this.paused) { return; } clearinterval(this.session); this.session = setinterval(minidaemon.forcecall, this.rate, this); }; minidaemon.prototype.pause = function () { clearinterval(this.session); this.paused = true; }; minidaemon.prototype.start = function (breverse) { var bbackw = boolean(breverse); if (this.backw === bbackw && (this.isatend() || !this.
...paused)) { return; } this.backw = bbackw; this.paused = false; this.synchronize(); }; minidaemon passes arguments to the callback function.
... mydaemon.synchronize() synchronize the timer of a started daemon with the time of its invocation.
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.
XMLHttpRequest.timeout - Web APIs
timeout shouldn't be used for synchronous xmlhttprequests requests used in a document environment or it will throw an invalidaccesserror exception.
... note: you may not use a timeout for synchronous requests with an owning window.
... 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.
XRReferenceSpace: reset event - Web APIs
most common among them are the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing.
... the webxr infrastructure or hardware drivers detected that the device had temporarily lost tracking, causing the hardware and software to be out of sync on position and orientation.
...when that happens, you typically hold down a button somewhere and it causes the world to resynchronize to the device's current orientation.
Array.prototype.forEach() - JavaScript
foreach expects a synchronous function foreach does not wait for promises.
... 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.
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.
... examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module 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 webassem...
...bly.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 definition of 'instance' in that specification.
JavaScript reference - JavaScript
dexed 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.
WebAssembly Concepts - WebAssembly
the different code types can call each other as required — the webassembly javascript api wraps exported webassembly code with javascript functions that can be called normally, and webassembly code can import and synchronously call normal javascript functions.
...given a webassembly instance, javascript code can synchronously call its exports, which are exposed as normal javascript functions.
... arbitrary javascript functions can also be synchronously called by webassembly code by passing in those javascript functions as the imports to a webassembly instance.
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.
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.
...the module does not automatically sync up a bookmark instance with ongoing changes to that item in the database from the same add-on, other add-ons, or the user.
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.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
although it was corrected in mozilla mainstream: mozilla/extensions/pref/autoconfig/src/nsldapsyncquery.cpp 1.7.2.1 by late 2004, it is still present in thunderbird 1.0.2 at least :-(, so i applied the workaround i proposed in that bug report (start_pos += 1;).
...v 04 21:34:18 cet 2011 defaults/preferences/ 604 fri nov 04 21:34:18 cet 2011 defaults/preferences/all-redhat.js 1389 fri nov 04 21:34:18 cet 2011 defaults/preferences/firefox-branding.js 76 fri nov 04 21:34:18 cet 2011 defaults/preferences/firefox-l10n.js 50295 fri nov 04 21:34:18 cet 2011 defaults/preferences/firefox.js 2470 fri nov 04 21:34:18 cet 2011 defaults/preferences/services-sync.js so there is no defaults/autoconfig/prefcalls.js and defaults/pref directory is now named defaults/preferences/ !
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).
Simple Storage - Archive of obsolete content
jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync().
...the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync().
Simple Storage - Archive of obsolete content
jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync().
...the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync().
Tamarin build documentation - Archive of obsolete content
running tamarin tests see running tamarin acceptance tests and running tamarin performance tests building tamarin windows mobile utilities the tamarin windows mobile utilities allows the existing acceptance and performance testsuites to be run on a windows mobile device connected to a windows desktop machine by activesync or windows mobile device center (for windows vista and windows 7).
... setup and run activesync or windows mobile device center.
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.
Textbox (XPFE autocomplete) - Archive of obsolete content
onend, selectionstart, sessioncount, showcommentcolumn, showpopup, size, tabindex, tabscrolling, textlength, textvalue, timeout, type, useraction, value methods addsession, clearresults, getdefaultsession, getresultat, getresultcount, getresultvalueat, getsession, getsessionbyname, getsessionresultat, getsessionstatusat, getsessionvalueat, removesession, select, setselectionrange, syncsessions examples (example needed) attributes accesskey type: character this should be set to a character that is used as a shortcut key.
... syncsessions( autocompleteelement ) obsolete since gecko 26 return type: void copy the sessions from another autocomplete element.
NPN_ForceRedraw - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary asks the plugin host to immediately (synchronously) repaint invalid areas.
...this causes a synchronous update event or paint message for the plug-in.
NPAPI plugin reference - Archive of obsolete content
npn_forceredraw asks the plugin host to immediately (synchronously) repaint invalid areas.
... 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).
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.
...uch 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.
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).
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately.
... note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks.
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge xmlhttprequest on wikipedia synchronous vs.
... asynchronous communications technical information the xmlhttprequest object.
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 ...
...cation speculative parsing speed index sql sql injection sri stacking context state machine statement static method static typing strict mode string stun style origin stylesheet svg svn symbol symmetric-key cryptography synchronous syntax syntax error synthetic monitoring t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls)...
How much does it cost to do something on the Web? - Learn web development
to do that you should use a publishing tool such as an (s)ftp client, rsync, or git/github.
... because ftp is inherently insecure, you should make sure to use sftp — the secure, encrypted version of ftp that most hosting sites you'll deal with these days will offer by default — or another secure solution like rsync over ssh.
What software do I need to build a website? - Learn web development
bear in mind that (s)ftp is now somewhat old-fashioned, and other uploading systems are starting to become popular, such as rsync and git/github.
...sftp or rsync over ssh.
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.
Working with Svelte stores - Learn web development
we could create a store that syncs its content to web storage, and later develop another one that syncs against a web service.
... a store may optionally contain a set() method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions.
Focus management with Vue refs - Learn web development
any updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch.
...however, it also means you often should not edit your html elements directly through native browser apis (like document.getelementbyid) when using frameworks, because it results in the vdom and real dom going out of sync.
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.
HTTP logging
use 'sync' if your browser crashes or hangs by default, http logging buffers messages and only periodically writes them to disk (this is more efficient and also makes logging less likely to interfere with race conditions, etc).
... however, if you are seeing your browser crash (or hang) you should add ",sync" to the list of logging modules in your moz_log environment variable.
Makefiles - Best practices and suggestions
parallel make: add an explicit timestamp dependency (.done) that make can synchronize threaded calls on to avoid a race condition.
... # transient directory for storing timestamps ts=.ts ##################################################### ## extra dep needed to synchronize parallel execution ##################################################### $(ts): $(ts)/.done $(ts)/.done: $(mkdir) -p $(dir $@) touch $@ # "clean" target garbage_dirs += $(ts) maintain clean targets - makefiles should be able to remove all content that is generated so "make clean" will return the sandbox/directory back to a clean state.
Eclipse CDT
if you click the yellow, double arrow button at the top of the project explorer tab on the left, it will keep the selected file in the project explorer tab in sync with the file that you're currently editing.
... resource is out of sync with the file system if you get the message "resource is out of sync with the file system", then you didn't set the "refresh" options above in the initial workspace preferences section.
Frame script environment
sendasyncmessage() send an asynchronous message to chrome.
... sendsyncmessage() send a synchronous message to chrome.
Frame script environment
sendasyncmessage() send an asynchronous message to chrome.
... sendsyncmessage() send a synchronous message to chrome.
Process scripts
bles 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.
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 wil...
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.
CustomizableUI.jsm
events are dispatched synchronously on the ui thread, so if you can delay any/some of your processing, that is advisable.
...during a batch update, the customization state is not saved to the user's preferences file, in order to reduce (possibly sync) io.
JavaScript OS.Constants
o_rsync o_shlock atomically obtain a shared lock.
... o_sync (linux only) open for purely synchronous access.
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 catch( function onreject ); the following calls are therefore identical: p.then(undefined, logerror); p.catch(logerror); debugging by design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method.
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.
Uplifting a localization from Central to Aurora
here some tips and tricks for syncing up both l10n-central and releases/l10n/mozilla-aurora at the same time en-us goes from central to aurora.
... you don't need to work on making the synchronization happen in either of your copies of the aurora or central repositories, but you can create a third one for this work.
MathML Accessibility in Mozilla
hence basic support is available in gecko 41.0 (firefox 41.0 / thunderbird 41.0 / seamonkey 2.38) and we are still trying to keep in sync with webkit/voiceover.
...we try to keep in sync with webkit/atk/orca developments.
I/O Functions
pr_open pr_delete pr_getfileinfo pr_getfileinfo64 pr_rename pr_access type praccesshow functions that act on file descriptors pr_close pr_read pr_write pr_writev pr_getopenfileinfo pr_getopenfileinfo64 pr_seek pr_seek64 pr_available pr_available64 pr_sync pr_getdesctype pr_getspecialfd pr_createpipe directory i/o functions pr_opendir pr_readdir pr_closedir pr_mkdir pr_rmdir socket manipulation functions the network programming interface presented here is a socket api modeled after the popular berkeley sockets.
...do not use pollable events for general thread synchronization; use condition variables instead.
Locks
prmonitor is intended for use with java and reflects the java approach to thread synchronization.
... for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr.
Monitors
unlike a mutex of type prlock, a mutex of type prmonitor has a single, implicitly associated condition variable that may be used to facilitate synchronization of threads with the change in state of monitored data.
... for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr.
PRIOMethods
syntax #include <prio.h> struct priomethods { prdesctype file_type; prclosefn close; prreadfn read; prwritefn write; pravailablefn available; pravailable64fn available64; prfsyncfn fsync; prseekfn seek; prseek64fn seek64; prfileinfofn fileinfo; prfileinfo64fn fileinfo64; prwritevfn writev; prconnectfn connect; pracceptfn accept; prbindfn bind; prlistenfn listen; prshutdownfn shutdown; prrecvfn recv; prsendfn send; prrecvfromfn recvfrom; prsendtofn sendto; prpollfn poll; pracceptreadfn acceptread; prtransmitfilefn transmitfile; prgetsocknamefn getsockname; prgetpeernamefn getpeername; prgetsockoptfn getsockopt; prsetsockoptfn setsockopt; }; typedef struct priomethods priomethods; p...
... fsync flush all in-memory buffers of file to permanent store.
PR_CreateThread
for more information on locks and thread synchronization, see introduction to nspr.
...you can then use pr_jointhread to synchronize the termination of another thread.
PR_JoinThread
description pr_jointhread is used to synchronize the termination of a thread.
... the function is synchronous in that it blocks the calling thread until the target thread is in a joinable state.
Threads
to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread).
... for api reference information related to thread synchronization, see locks and condition variables.
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.
TPS Formdata Lists
{ fieldname: "username", value: "joe" } ]; formdata lists and phase actions you can use the following functions in phase actions for formdata lists: formdata.add formdata.delete formdata.verify formdata.verifynot for an example, see the tps formdata unittest: http://hg.mozilla.org/services/tps/f...st_formdata.js notes note 1, tps supports the delete action for formdata, but sync currently does not correctly sync deleted form data, see bug 564296.
... note 2, sync currently does not sync formdata dates, so the date field is ignored when performing verify and verify-not actions.
TPS Pref Lists
for example: var prefs1 = [ { name: "browser.startup.homepage", value: "http://www.getfirefox.com" }, { name: "browser.urlbar.maxrichresults", value: 20 }, { name: "browser.tabs.autohide", value: true } ]; pref lists and phase actions the only actions supported for preference asset lists are modify and verify: prefs.modify prefs.verify sync only syncs certain preferences.
... to find the list of valid preferences, go to about:config on a browser that has weave installed, and search for services.sync.prefs.sync.
Web Replay
the data stream should have enough error checking in place that we can immediately detect if the replay has gone out of sync with the recording.
... the middleman can perform actions that would be extremely difficult to manage in a replaying process without going out of sync with the recording.
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.
... > r.set('foo', 42, console.log) null 'ok' > r.get('foo', console.log) null '42' for the rest of this, i'm going to use the synchronous redis-cli for demonstrations.
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.
imgIContainer
flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call returns.
... flag_sync_decode 0x1 flag_decode_no_premultiply_alpha 0x2 flag_decode_no_colorspace_conversion 0x4 flag_clamp 0x8 frame_first 0 constants for specifying various "special" frames.
imgIRequest
note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest().
...aobserver will be notified synchronously (before the clone call returns) with all the notifications that have already been dispatched for this image load.
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 ...
nsIAppShell
runinstablestate() allows running of a "synchronous section", in the form of an nsirunnable once the event loop has reached a "stable state".
... a stable state is reached when the currently executing task/event has finished, (see: webappapis.html#synchronous-section).
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.
nsIBrowserSearchService
to access this service, use: var browsersearchservice = components.classes["@mozilla.org/browser/search-service;1"] .getservice(components.interfaces.nsibrowsersearchservice); attempting to use any method or attribute of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization.
... attempting to call any method of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization.
nsICache
non_blocking 0 the synchronous opencacheentry() may be blocking or non-blocking.
... blocking 1 the synchronous opencacheentry() may be blocking or non-blocking.
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.
nsIContentFrameMessageManager
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisyncmessagesender this interface provides the environment for scripts that are loaded into content frames using the nsiframescriptloader interface.
... 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.
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.
nsIDownloadManager
note: prior to gecko 12.0, this was a synchronous operation; that is, once this method returned, you knew that the download was in the download manager's list.
...adding downloads to the download manager is now an asynchronous operation.
nsIEventTarget
dispatch_sync 1 this flag specifies the synchronous mode of event dispatch, in which the dispatch() method does not return until the event has been processed.
...method for posting an asynchronous event to the event target.
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
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?
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.
...e.g., header=filter return the nsiuri that gets run example for example, the next piece of code shows the selected message code on a dialog: (taken from mozillazine) var content = ""; var messageuri = getfirstselectedmessage(); var msgservice = messenger.messageservicefromuri(messageuri); var msgstream = components.classes["@mozilla.org/network/sync-stream-listener;1"].createinstance(); var consumer = msgstream.queryinterface(components.interfaces.nsiinputstream); var scriptinput = components.classes["@mozilla.org/scriptableinputstream;1"].createinstance(); var scriptinputstream = scriptinput.queryinterface(components.interfaces.nsiscriptableinputstream); scriptinputstream.init(consumer); try { msgservice.streammessage(messageu...
nsINavBookmarksService
this method retrieves a globally unique identifier for an item, meant to be used in sync scenarios.
...this can be useful when a sync algorithm deems two independently created items (on different profiles) to be the same item.
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.
nsISelectionController
selection_on 2 selection_disabled 3 selection_attention 4 scroll constants constant value description scroll_synchronous 1<<1 if set scrolls the selection into view before returning.
...note: if issynchronous is true, calling this method may flush the pending reflow.
nsIThread
warning: calling nsithread.processnextevent allows network and ui events to run which can modify data structures that your code isn't expecting to be modified during a synchronous method call.
...consider use asynchronous callbacks instead.
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.
Index
9 address book sync client design by richard h.
...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.
Mail and RDF
asynchronously notifying rdf when the data itself changes, rdf needs to be notified.
...f.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.
Using COM from js-ctypes
tdcall *speak)(struct myispvoice*, lpcwstr pwcs, dword dwflags, ulong* pulstreamnumber); void* speakstream; void* getstatus; void* skip; void* setpriority; void* getpriority; void* setalertboundary; void* getalertboundary; void* setrate; void* getrate; void* setvolume; void* getvolume; void* waituntildone; void* setsyncspeaktimeout; void* getsyncspeaktimeout; void* speakcompleteevent; void* isuisupported; void* displayui; /* end ispvoice */ }; int main(void) { if (succeeded(coinitialize(null))) { struct myispvoice* pvoice = null; hresult hr = cocreateinstance(&clsid_spvoice, null, clsctx_all, &iid_ispvoice, (void**)&pvoice); ...
... ctypes.voidptr_t }, { 'setpriority': ctypes.voidptr_t }, { 'getpriority': ctypes.voidptr_t }, { 'setalertboundary': ctypes.voidptr_t }, { 'getalertboundary': ctypes.voidptr_t }, { 'setrate': ctypes.voidptr_t }, { 'getrate': ctypes.voidptr_t }, { 'setvolume': ctypes.voidptr_t }, { 'getvolume': ctypes.voidptr_t }, { 'waituntildone': ctypes.voidptr_t }, { 'setsyncspeaktimeout': ctypes.voidptr_t }, { 'getsyncspeaktimeout': ctypes.voidptr_t }, { 'speakcompleteevent': ctypes.voidptr_t }, { 'isuisupported': ctypes.voidptr_t }, { 'displayui': ctypes.voidptr_t } // end ispvoice ]); // functions // http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279%28v=vs.85%29.aspx let coinitializeex = lib.declare('coinitializeex', winabi, ...
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.
Frame rate - Firefox Developer Tools
a frame rate of 60fps is reckoned to be the target for smooth performance, giving you a time budget of 16.7ms for all the updates that need to be made synchronously in response to some event.
...the intensive javascript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous javascript.
Animation.updatePlaybackRate() - Web APIs
the updateplaybackrate() method of the web animations api's animation interface sets the speed of an animation after first synchronizing its playback position.
... 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.
... animation.updateplaybackrate() sets the speed of an animation after first synchronizing its playback position.
CanvasRenderingContext2D.drawWindow() - Web APIs
it is synchronous, and as such can't be compatible with fission.
... drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have.
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('l...
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.
EventTarget.dispatchEvent() - Web APIs
dispatches an event at the specified eventtarget, (synchronously) invoking the affected eventlisteners in the appropriate order.
... notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously.
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.
FileException - Web APIs
in the file system api, a fileexception object represents error conditions that you might encounter while accessing the file system using the synchronous api.
... basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors.
FileHandle API - Web APIs
such a file object is completely desynchronized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the file object.
...periodically, the results of those operation are asynchronously flushed to the device storage area.
HTMLCanvasElement.getContext() - Web APIs
desynchronized: boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop (gecko only) willreadfrequently: boolean that indicates whether or not a lot of read-back operations are planned.
... desynchronized: boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop antialias: boolean that indicates whether or not to perform anti-aliasing.
HTMLMediaElement.seekToNextFrame() - Web APIs
the htmlmediaelement.seektonextframe() method asynchronously advances the the current play position to the next frame in the media.
... firefox 49 returns undefined instead of a promise, and performs the seek operation synchronously.
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.
Locks.name - Web APIs
WebAPILockname
for example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as "net_db_sync".
... navigator.locks.request("net_db_sync", show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comment web locks apithe definition of 'name' in that specification.
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.
OffscreenCanvas - Web APIs
examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate new frames.
... // 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.
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 { ...det...
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.
...ata 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 => { ...
PerformanceEventTiming - Web APIs
examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing time (between start and end dispatch).
... const inputsyncprocessingtime = entry.processingend - entry.processingstart; }); }); // register observer for event.
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 - Web APIs
localid a domstring which is used to find the local rtcinboundrtpstreamstats object which shares the same synchronization source (ssrc).
...be aware that the remote clock may not be synchronized with the local clock (either in current time or speed at which time elapses).
RTCRtpContributingSource.audioLevel - Web APIs
for both rtcrtpcontributingsource and rtcrtpsynchronizationsource, the audio level is converted to this form from the values defined in the specifications corresponding to each type of source.
... audiolevel may be absent from rtcrtpcontributingsource objects, which indicates that no volume level was provided by the source; however, it is required and always available on all rtcrtpsynchronizationsource objects.
RTCRtpContributingSource.source - Web APIs
the value is the contributing source (csrc) or synchronization source (ssrc) identifier, depending on whether the object is an rtcrtpcontributingsource or rtcrtpsynchronizationsource, which is based on the former.
... syntax var sourceid = rtcrtpcontributingsource.source value an unsigned, 32-bit integer value which uniquely identifies the source of rtp packets described by this rtcrtpcontributingsource (in which case the value is a csrc identifier) or rtcrtpsynchronizationsource (the value is an ssrc identifier).
RTCRtpStreamStats.ssrc - Web APIs
the rtcrtpstreamstats dictionary's ssrc property provides the synchronization source (ssrc), an integer which uniquely identifies the source of the rtp packets whose statistics are covered by the rtcstatsreport that includes this rtcrtpstreamstats dictionary.
... syntax var ssrc = rtcrtpstreamstats.ssrc; value the synchronization source (ssrc) is a 32-bit integer uniquely identifying the source of the rtp packets whose statistics are covered by the rtcstatsreport object of which this rtcrtpstreamstats object is a component.
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...
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); specif...
registration - Web APIs
the registration read-only property of the syncevent interface returns a reference to a syncregistration object.
... syntax var syncreg = syncevent.registration value a syncregistration object ...
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) { ...
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.
WebGL constants - Web APIs
uniform_is_row_major 0x8a3e uniform_block_binding 0x8a3f uniform_block_data_size 0x8a40 uniform_block_active_uniforms 0x8a42 uniform_block_active_uniform_indices 0x8a43 uniform_block_referenced_by_vertex_shader 0x8a44 uniform_block_referenced_by_fragment_shader 0x8a46 sync objects constant name value description object_type 0x9112 sync_condition 0x9113 sync_status 0x9114 sync_flags 0x9115 sync_fence 0x9116 sync_gpu_commands_complete 0x9117 unsignaled 0x9118 signaled 0x9119 already_signaled 0x911a ...
... timeout_expired 0x911b condition_satisfied 0x911c wait_failed 0x911d sync_flush_commands_bit 0x00000001 miscellaneous constants constant name value description color 0x1800 depth 0x1801 stencil 0x1802 min 0x8007 max 0x8008 depth_component24 0x81a6 stream_read 0x88e1 stream_copy 0x88e2 static_read 0x88e5 static_copy 0x88e6 dynamic_read 0x88e9 dynamic_copy 0x88ea depth_component32f 0x8cac depth32f_stencil8 0x8cad invalid_index 0xffffffff tim...
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
reference standard interfaces webglrenderingcontext webgl2renderingcontext webglactiveinfo webglbuffer webglcontextevent webglframebuffer webglprogram webglquery webglrenderbuffer webglsampler webglshader webglshaderprecisionformat webglsync webgltexture webgltransformfeedback webgluniformlocation webglvertexarrayobject extensions angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel_sh...
...it is based on opengl es 3.0 and new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex array objects, instancing, multiple render targets, fragment depth.
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...
...this figure goes by a number of different names, but they're all equivalent or nearly so: refresh rate vertical refresh rate vertical blanking rate (vbl) vertical sync rate vertical refresh rate there are other similar terms used as well, but regardless of what it's called, the unit of measurement applied is the hertz, or hz.
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.
Using the Web Storage API - Web APIs
next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page.
...this won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made.
Using Web Workers - Web APIs
this is done synchronously; importscripts() does not return until all the scripts have been loaded and executed.
...they will also allow access to push notifications and background sync apis.
Window.mozAnimationStartTime - Web APIs
this value should be used instead of, for example, date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another.
... this also allows javascript-based animations to remain synchronized with css transitions and smil animations triggered during the same refresh interval.
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().
....org/mime;1"] .getservice(components.interfaces.nsimimeservice); mimetype = mimeservice.gettypefromfile(file); // file is an nsifile instance } catch (oevent) { /* eat it; just use text/plain */ } // send var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); req.open('put', url, false); /* synchronous!
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.
... if the request is synchronous, this method doesn't return until the response has arrived.
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
the screen reader user can navigate the web page using screen reader commands or browser commands, and the two pieces of software must remain in sync.
...such a cache must be kept in perfect sync with the tree of ui and document objects, which is difficult.
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.
WAI ARIA Live Regions/API Support - Developer guides
this information is retrieved differently on each platform, because some platforms use asynchronous events.
...they are synchronous with what the user is doing and can thus likely be read without disorienting the user.
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.
Video player styling basics - Developer guides
this means that a user could play/pause the video from these controls, which would then leave the custom control set's buttons out of sync.
... if a user uses the default controls, the defined media api events — such as play and pause — are raised so this can be taken advantage of to ensure that the custom control buttons are kept in sync.
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.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
allowed values: sync decode the image synchronously, for atomic presentation with other content.
... async decode the image asynchronously, to reduce delay in presenting other content.
Using Feature Policy - HTTP
these features include: layout-inducing animations unoptimized (poorly compressed) images oversized images synchronous scripts synchronous xmlhttprequest unsized media to avoid breaking existing web content, the default for such policy-controlled features is to allow the functionality to be used by all origins.
... send the following the http header: feature-policy: layout-animations 'none'; unoptimized-images 'none'; oversized-images 'none'; sync-script 'none'; sync-xhr 'none'; unsized-media 'none'; using the <iframe> allow attribute: <iframe src="https://example.com..." allow="layout-animations 'none'; unoptimized-images 'none'; oversized-images 'none'; sync-script 'none'; sync-xhr 'none'; unsized-media 'none';"></iframe> ...
Feature Policy - HTTP
block the use of outdated apis like synchronous xhr and document.write().
... the features include: layout-inducing animations legacy image formats oversized images synchronous scripts synchronous xmlhttprequest unoptimized images unsized media granular control over certain features the web provides functionality and apis that may have privacy or security risks if abused.
HTTP Index - HTTP
WebHTTPIndex
144 feature-policy: sync-xhr directive, feature policy, feature-policy, http, reference, xmlhttprequest the http feature-policy header sync-xhr directive controls whether the current document is allowed to make synchronous xmlhttprequest requests.
...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.
Concurrency model and the event loop - JavaScript
event loop the event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitformessage()) { queue.processnextmessage() } queue.waitformessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled).
... legacy exceptions exist like alert or synchronous xhr, but it is considered a good practice to avoid them.
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.
The arguments object - JavaScript
non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa: function func(a) { arguments[0] = 99; // updating arguments[0] also updates a console.log(a); } func(10); // 99 and also: function func(a) { a = 99; // updating a also updates arguments[0] console.log(arguments[0]); } func(10); // 99 conversely, non-strict functions that are pass...
...ed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object.
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); //...
SharedArrayBuffer - JavaScript
var sab = new sharedarraybuffer(1024); worker.postmessage(sab); updating and synchronizing shared memory with atomic operations shared memory can be created and updated simultaneously in workers or the main thread.
...to synchronize, atomic operations are needed.
WebAssembly.Instance - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module 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 webassem...
...bly.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 functions.
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...
2015 MDN Fellowship Program - Archive of obsolete content
they enable the creation of effective offline experiences and wiill also allow access to push notifications and background sync apis.
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.
net/url - Archive of obsolete content
options : object optional options: name type sync boolean if this option is set to true, the promise returned will be resolved synchronously.
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.
stylesheet/utils - Archive of obsolete content
globals functions loadsheet(window, uri, type) synchronously loads a style sheet from uri and adds it to the list of additional style sheets of the document.
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
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...
Preferences - Archive of obsolete content
bes preferences system from user's/administrator's pov mozilla xpcom interfaces of the preferences system most used interfaces (these are frozen and will not change): nsiprefbranch and nsiprefservice nsiprefbranch2 interface (before gecko 1.8 it was called nsiprefbranchinternal) preferences system - an easy way to create a xul options window for your extension or application syncing preferences across clients using sync lxr pages for libpref, the source code module that implements the preferences system a javascript wrapper for preferences api adding preferences to an extension — a simple tutorial with a working extension that illustrates the use of preference observers inline options - how to use the new preference ui that appears inline in the add-on manager windo...
JavaScript timers - Archive of obsolete content
a block of javascript code is generally executed synchronously.
Enhanced Extension Installation - Archive of obsolete content
the format here is similar to firefox 1.0 except there is no longer a count value that needs to be kept in sync with the number of lines...
How to convert an overlay extension to restartless - Archive of obsolete content
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...
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.
Appendix A: Add-on Performance - Archive of obsolete content
never use xmlhttprequest in synchronous mode.
Custom XUL Elements with XBL - Archive of obsolete content
this is likely due to some asynchronous operation related to node insertion.
JavaScript Object Management - Archive of obsolete content
javascript code modules javascript code modules (also known as jsm) are new to firefox 3, and they're the best tool for keeping everything in sync between windows.
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.
Using the Stylesheet Service - Archive of obsolete content
heet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("chrome://myext/content/myext.css", null, null); sss.loadandregistersheet(uri, sss.user_sheet); note: loadandregistersheet will load the stylesheet synchronously, so you should only call this method using local uris.
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.
List of Former Mozilla-Based Applications - Archive of obsolete content
homebase desktop operating environment for internet computers no longer available hp printer assistant printer utility hall of fame page mentions that this used an embedded version of mozilla at some point but i can't find reference to current status (may still be using mozilla code?) icebrowser java browser sdk uses mozilla rhino --eol'ed in 2009 (jin'sync) office app launcher download page last updated on 12/21/06 kylix compiler and integrated development environment borland discontinued this product.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
nsiwindowwatcher windowproxy = (nsiwindowwatcher)proxy.getproxyforobject(eventqueue,windowwatcher.ns_iwindowwatcher_iid,windowwatcher,nsiproxyobjectmanager.invoke_sync); // now we use the proxy to call the method as usual.
Block and Line Layout Cheat Sheet - Archive of obsolete content
ns_frame_sync_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the frame's bounding box.
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
,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.
Tamarin Acceptance Testing - Archive of obsolete content
misc the acceptance and performance tests can be run on windows mobile devices connected to windows desktop machine with activesync.
Tamarin Build System Documentation - Archive of obsolete content
the performance and deep phases do not run synchronously.
Tamarin mercurial commit hook - Archive of obsolete content
installing the commit hook the easiest way to implement the hook is to sync to the tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook.
Tuning Pageload - Archive of obsolete content
since layout and painting happen asynchronously, while the parser is working there is no layout or painting.
DOM Interfaces - Archive of obsolete content
loadbindingdocument the loadbindingdocument method can be used to synchronously obtain the specified binding document for use within a particular document (the one on which the loadbindingdocument method was invoked).
Using XPInstall to Install Plugins - Archive of obsolete content
// by passing 'true' we are telling the install script to block // on the execution of the installable, and do it synchronously // must call performinstall to make it all happen...
visuallyselected - Archive of obsolete content
the visuallyselected attribute is set asynchronously, once the browser has switched to the selected tab.
Index - Archive of obsolete content
ArchiveMozillaXULIndex
589 syncsessions needshelp, xul methods, xul reference no summary!
Methods - Archive of obsolete content
lection removenotification removeprogresslistener removesession removetab removetabsprogresslistener removetransientnotifications replacegroup reset rewind scrollbyindex scrollbypixels scrolltoindex select selectall selectitem selectitemrange selecttabatindex setselectionrange showpane showpopup sizeto startediting stop stopediting swapdocshells syncsessions timedselect toggleitemselection related dom element methods dom:element.addeventlistener dom:element.appendchild dom:element.comparedocumentposition dom:element.dispatchevent dom:element.getattribute dom:element.getattributenode dom:element.getattributenodens dom:element.getattributens dom:element.getelementsbytagname dom:element.getelementsbytagnamens dom:elem...
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.
XUL accessibility guidelines - Archive of obsolete content
video a video file can be made accessible by adding synchronized captions.
prefpane - Archive of obsolete content
for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that returns the value to be written to the preference element, and then call the userchangedvalue function every time you edit the list in a way that should cause the preference's value to change.
Deploying XULRunner - Archive of obsolete content
make sure you copy all symlinks correctly (use rsync -rl /library/frameworks/xul.framework ...).
Getting started with XULRunner - Archive of obsolete content
it also means that the xulrunner is portable so, if you develop your applications to be portable you could carry them around on a flash drive or sync them in the cloud.
mozilla.dev.platform FAQ - Archive of obsolete content
took an foo.app directory created with xulrunner-bin --install-app and tried to copy (using rsync -rl) the xul.framework directory into a frameworks directory in the .app bundle and then deleting the xul.framework directory from /library/frameworks, my running my app fails silently.
Archived Mozilla and build documentation - Archive of obsolete content
firefox sync sync refers to a family of related components and services which provide synchronization of data between mozilla application instances.
Gecko Compatibility Handbook - Archive of obsolete content
since a web page is judged not by how well it is written but by how well it displays in a browser, authors have developed many techniques which take advantage of idiosyncracies in particular browsers to achieve the desired effect.
2006-11-10 - Archive of obsolete content
discussions help about firefox 3 a discussion on how to syncronise mozilla_1_8_branch with the trunk, which tag should be used to check-in files on trunk, and when files will be pulled from trunk to create another branch (mozilla_1_9_branch?) for firefox 3.
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.
SAX - Archive of obsolete content
efixmapping: 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.
Common Firefox theme issues and solutions - Archive of obsolete content
address bar "door hangers" door hanger sync panel not styled the sync panel at the bottom of the "door hanger" for the save password panel displayed when a user logs into a website needs to be styled to match rest of panel including border.
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.
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.
Finishing up - Game development
it will sync the framerate accordingly and render the shapes only when needed.
Visual typescript game engine - Game development
find configuration at ./src/lib/client-config.ts /** * addson * all addson are ansync loaded scripts.
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.
Progressive web apps - MDN Web Docs Glossary: Definitions of Web-related terms
these features include being installable, working offline, and being easy to sync with and re-engage the user from the server.
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.
Transmission Control Protocol (TCP) - MDN Web Docs Glossary: Definitions of Web-related terms
the three messages transmitted by tcp to negotiate and start a tcp session are nicknamed syn, syn-ack, ack for synchronize, synchronize-acknowledgement, and acknowledge.
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.
How to build custom form controls - Learn web development
as seen previously, we already use a native select control as a fallback for accessibility reasons; we can simply synchronize its value with that of our custom control: // this function updates the displayed value and synchronizes it with the native control.
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).
Video and audio content - Learn web development
captions synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
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 Interactivity: Footer functionality, conditional rendering - Learn web development
however, because *eventually*, we'll want to persist or sync all changes to the todos list to local storage (see the final version of the app), it makes sense to have all persistent-state-changing operations be in the same place.
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.
Dynamic behavior in Svelte: working with variables and props - Learn web development
to do that we need to bind our newtodoname variable to the todo-0 input, so that the newtodoname variable value stays in sync with the input's value property.
Handling common accessibility problems - Learn web development
most modern browsers follow the tab pattern described above (you can also do shift + tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies: firefox for the mac doesn't do tabbing by default.
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.
Mozilla’s UAAG evaluation report
(p1) na this relates to multimedia players 2.6 respect synchronization cues.
Command line options
--sync make x calls synchronous.
Debugging OpenGL
this flushes out each call, essentially turning opengl into a synchronous api.
Simple Instantbird build
this should be kept in sync with simple thunderbird build, you might want to take a look at that page too.
Simple SeaMonkey build
run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 yasm problems?
Simple Sunbird build
run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 problems?
Eclipse CDT Manual Setup
select "general > workspace" and select "refresh using native hooks or polling" and "refresh on access" to prevent eclipse giving you annoying "resource is out of sync" messages when files change from under it due to mercurial or other external activity.
Displaying Places information using views
doing so circumvents updating the view's place attribute, causing it to fall out of sync with the view's query result.
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.
Message manager
guides message manager overview frame script loading and lifetime communicating with frame scripts performance best practices frame script environment limitations of frame scripts process scripts api reference nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster nsimessagesender nsisyncmessagesender nsicontentframemessagemanager nsiprocessscriptloader ...
Multiprocess Firefox
cross process object wrappers cross process object wrappers are a migration aid, giving chrome code synchronous access to web content.
Firefox and the "about" protocol
(question mark) > troubleshooting information) about:sync-log displays a synchronization protocol related to the sync feature about:telemetry displays telemetry data collected and sent to mozilla while firefox is running (in case the user enabled telemetry) about:url-classifier displays the status of the url classifier services that firefox uses (for example for safe browsing) about:webrtc information about webrtc ...
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
otcached 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 ...
Chrome-only Events reference
mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized.
Embedding Tips
it is left as an exercise to make this sample synchronous, i.e.
Creating a New Protocol
it is acceptable to use synchronous calls on jpw wrappers for testing purposes.
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.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.
WebRequest.jsm
in particular, "blocking" may be passed to several event types, and will make the event dispatch synchronous, so the browser will wait for the event listener to return before continuing with the request.
Localizing with Pontoon
actually, it does that for you by automatically syncing with repositories on hourly basis.
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.
Gecko Profiler FAQ
are the timer probes synchronized, or random/independent?
A brief guide to Mozilla preferences
they are: default preference files firefox ships default preferences in several files, all in the application directory: greprefs.js - preferences shared by all applications using the mozilla platform services/common/services-common.js - preferences for some shared services code, this should arguably be included in some other file defaults/pref/services-sync.js - default preferences for firefox sync, also oddly misplaced browser/app/profile/channel-prefs.js - a file indicating the user's update channel.
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.
Cached Monitors
cached monitors functions cached monitors allow the client to associate monitoring protection and state change synchronization in a lazy fashion.
Condition Variables
for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr.
Dynamic Library Linking
this section summarizes these platform idiosyncrasies.
NSPR LOG MODULES
sync the name sync enables unbuffered logging.
PRThreadPriority
this preference is still subject to resource availability and must not be used in place of proper synchronization.
PRThreadState
the join process permits strict synchronization of thread termination and therefore promotes effective resource management.
PRThreadType
nspr allows the client to synchronize the termination of all user threads and ignores those created as system threads.
PR_Cleanup
pr_cleanup attempts to synchronize the natural termination of the process.
PR_Open
pr_sync 0x40 if set, each write will wait for both the file data and file status to be physically updated.
PR_SetThreadPrivate
synchronization is the client's responsibility.
NSPR API Reference
introduction to nspr nspr naming conventions nspr threads thread scheduling setting thread priorities preempting threads interrupting threads nspr thread synchronization locks and monitors condition variables nspr sample code nspr types calling convention types algebraic types 8-, 16-, and 32-bit integer types signed integers unsigned integers 64-bit integer types floating-point integer type native os integer types miscellaneous types size type pointer difference types boolean types status type for return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities contr...
NSS 3.12.9 release notes
bug 609068: implement j-pake in freebl bug 607058: crash [@ nss_cms_decoder_work_data] bug 613394: november/december 2010 batch of nss root ca changes bug 610843: need way to recover softoken in child after fork() bug 617492: add pk11_keygenwithtemplate function to pk11wrap (for firefox sync) bug 610162: sha-512 and sha-384 hashes are incorrect for inputs of 512mb or larger when running under windows and other 32-bit platforms (fx 3.6.12 and 4.0b6) bug 518551: vfychain crashes in pkits tests.
NSS 3.35 release notes
(conversely, nss will never synchronize data from sql to dbm format.) additional information can be found on this fedora linux project page: https://fedoraproject.org/wiki/changes/nssdefaultfileformatsql added formally verified implementations of non-vectorized chacha20 and non-vectorized poly1305 64-bit.
NSS 3.44 release notes
ackage() 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...
The JavaScript Runtime
any host objects that are defined are responsible for any synchronization required to run safely from multiple threads.
FOSS
http://javalikescript.free.fr/ - a general-purpose javascript platform that aims to provide an extensible tooling framework http://www.synchro.net/ - a telnet/ssh bulletin board system (bbs) and internet server (http/smtp/ftp) with extra internet services written in javascript (irc, imap, gopher, and many more) https://github.com/mindbit/libjssql/wiki - a library that aims to provide a generic sql api for javascript that is as similar as possible to jdbc miscellaneous serverjs, a standardization effort for the fragmented...
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
058695) 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::...
Thread Sanitizer
unlike other tools, it understands compiler-builtin atomics and synchronization and therefore provides very accurate results with no real false positives.
Secure Development Guidelines
n the file”); } fd = open(file, o_rdwr); write(fd, argv[2], strlen(argv[2])); } file i/o: race conditions previous example contains a race condition the file may change between the call top stat() and open() this opens the possibility of writing arbitrary content to any file race conditions occur when two separate execution flows share a resource and its access is not synchronized properly race condition types include file (previously covered) thread (two threads share a resource but don’t lock it) signal race conditions example char *ptr; void sighandler() { if (ptr) free(ptr); _exit(0); } int main() { signal(sigint, sighandler); ptr = malloc(1000); if (!ptr) exit(0); ...
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 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.
Starting WebLock
as a layer of abstraction above the operating system, the nspr allows gecko applications to be platform independent by providing the following system-level facilities: threads thread synchronization file and network i/o timing and intervals memory management shared library linking the nspr is included in the gecko sdk.
Components.utils
please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context.
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); vo...
mozIJSSubScriptLoader
method overview jsval loadsubscript(in string url, in object targetobj optional, in string charset optional); jsval loadsubscriptwithoptions(in string url, in object options); methods loadsubscript() synchronously loads and executes the script from the specified url.
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.
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.
nsIDOMWindowUtils
loadsheet() synchronously loads a style sheet from |sheeturi| and adds it to the list of additional style sheets of the document.
nsIEditor
void begintransaction(); void endtransaction(); void beginplaceholdertransaction(in nsiatom name); void endplaceholdertransaction(); boolean shouldtxnsetselection(); void setshouldtxnsetselection(in boolean should); inline spellchecking methods nsiinlinespellchecker getinlinespellchecker(in boolean autocreate); void syncrealtimespell(); void setspellcheckuseroverride(in boolean enable); clipboard methods void cut(); boolean cancut(); void copy(); boolean cancopy(); void paste(in long aselectiontype); boolean canpaste(in long aselectiontype); selection methods void selectall(); void beginningofdocument(); vo...
nsIFeedContainer
methods normalize() synchronizes a container's fields with its convenience attributes.
nsIFilePicker
open() opens the file dialog asynchrounously.
nsIFocusManager
void contentremoved( in nsidocument adocument, in nsicontent aelement ); parameters adocument aelement native code only!firedelayedevents fire any events that have been delayed due to synchronized actions.
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...
nsILocalFile
pr_sync if set, each write will wait for both the file data and file status to be physically updated.
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.
nsIMessageListenerManager
dom/base/nsimessagemanager.idlscriptable this interface enables clients to listen for messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces.
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.
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.
nsINavHistoryObserver
it's possible for a history entry to be deleted even though it has no visits if something is out of sync after a bookmark with no visits is deleted; this results in the entire history entry being freed).
nsINavHistoryResultNode
using places services after quit-application is not reliable, so make sure to do any shutdown work on quit-application, or history synchronization could fail, losing latest changes.
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.
nsIScriptableIO
syncsave: writing methods do not return until the data is properly saved.
nsISocketTransportService
the notification is asynchronous, delivered via the given nsirunnable instance on the socket transport thread.
nsIStyleSheetService
boolean sheetregistered(in nsiuri sheeturi, in unsigned long type); void unregistersheet(in nsiuri sheeturi, in unsigned long type); constants constant value description agent_sheet 0 user_sheet 1 author_sheet 2 methods loadandregistersheet() synchronously loads a style sheet from sheeturi and adds it to the list of user or agent style sheets.
nsITelemetry
al 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...
nsIToolkitProfileService
warning: this service is synchronous so it is recommended that you use os.file to find the profile directory via os.constants.path.profiledir.
nsITreeBoxObject
this must be followed by calling endupdatebatch(), otherwise the tree will get out of sync.
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().
nsIXULTemplateBuilder
the builder will resynchronize any variables that are referenced in the action body.
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.
XPCOM
like the standard libraries, xpcom must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies.xpcom thread synchronizationxpcom thread synchronization primitives have the same semantics as those in nspr, and each method of these synchronization objects (e.g.
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) { ...
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.
The libmime module
the definition of these classes is somewhat idiosyncratic and consists of an internally defined object system, instead of c++.
Thunderbird API documentation
activity manager address book sync client design buddy icons in mail composition composition back end in mail cached compose window faq filelink providers new!
Working with windows in chrome code
you could declare a local variable in each window along with corresponding setter functions to keep the "instances" of the variable in sync across windows, but fortunately, there's a better way.
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
d, 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/...
Mozilla
it synchronously returns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace.
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).
Scripting plugins - Plugins
the threading model for this api is such that all calls through this api are synchronous and calls from a plugin to methods in this api must come from the thread on which the plugin was initiated, and likewise all calls to methods in this api by the browser are guaranteed to come from the same thread.
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.
UI Tour - Firefox Developer Tools
correlating events because these elements are synchronized, you can correlate events in one element with events in another.
about:debugging - Firefox Developer Tools
until such time as firefox for android is updated to a newer major release, in synch with desktop firefox, you should use one of the following firefox for android versions: firefox preview, if your desktop firefox is the main release or developer edition firefox for android nightly if you prefer to test with the main release of firefox for android (i.e., based on release 68), you can do so with the desktop firefox extended support release (esr), which is also based on vers...
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.startTime - Web APIs
examples in the running on web animations api example, the we can sync all new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes new cats.
Animation.timeline - Web APIs
a timeline is a source of time values for synchronization purposes, and is an animationtimeline-based object.
AudioWorkletProcessor.process - Web APIs
the method is called synchronously from the audio rendering thread, once for each block of audio (also known as a rendering quantum) being directed through the processor's corresponding audioworkletnode.
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.
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.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.getElementsByTagName() - Web APIs
the returned htmlcollection is live, meaning that it updates itself automatically to stay in sync with the dom tree without having to call document.getelementsbytagname() again.
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 even...
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 specific...
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 specificat...
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.
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.
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
de(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...
onMSVideoOptimalLayoutChanged - Web APIs
syntax value description event property object.onmsvideooptimallayoutchanged = handler; attachevent method object.attachevent("onmsvideooptimallayoutchanged", handler) addeventlistener method object.addeventlistener("", handler, usecapture) synchronous no bubbles no cancelable no see also msislayoutoptimalforplayback htmlvideoelement microsoft api extensions ...
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.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
the main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations.
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.
IDBObjectStore.deleteIndex() - Web APIs
note that this method synchronously modifies the idbobjectstore.indexnames property.
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.
Keyboard.unlock() - Web APIs
WebAPIKeyboardunlock
the unlock() method of the keyboard interface unlocks all keys captured by the keyboard.lock() method and returns synchronously.
Keyboard - Web APIs
WebAPIKeyboard
keyboard.unlock() unlocks all keys captured by the lock() method and returns synchronously.
Lock - Web APIs
WebAPILock
navigator.locks.request("net_db_sync", show_lock_properties); navigator.locks.request("another_lock", {mode: "shared"}, show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comment web locks apithe definition of 'lock' in that specification.
MSCandidateWindowHide - Web APIs
general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event.
MSCandidateWindowShow - Web APIs
general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event.
MSCandidateWindowUpdate - Web APIs
general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event.
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...
MediaTrackSettings - Web APIs
if the value can't be determined for any reason, the value will match the vertical sync rate of the device the user agent is running on.
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.
Online and offline events - Web APIs
effectively, the requirements break down as such: you need to know when the user comes back online, so that you can re-synchronize with the server.
Node.appendChild() - Web APIs
WebAPINodeappendChild
note that the copies made with clonenode will not be automatically kept in sync.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
note that the copies made with clonenode() will not be automatically kept in sync.
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
note the idiosyncratic argument order (new before old).
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.
NotificationEvent.action - Web APIs
example self.registration.shownotification("new articles available", { actions: [{action: "get", title: "get now."}] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizereader(); } else { clients.openwindow("/reader"); } }, false); specifications specification status comment notifications apithe definition of 'action' in that specification.
OfflineAudioContext.suspend() - Web APIs
this is generally useful at the time of manipulating the audio graph synchronously on offlineaudiocontext.
PaymentAddress - Web APIs
nation", 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.
Payment Request API - Web APIs
a browser can also sync these "credentials" across devices, making it easy for users to jump from desktop to mobile and back again when buying things.
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.
Permissions - Web APIs
safari ios no support nosamsung internet android full support 8.0background-sync permissionchrome full support 62edge full support 79firefox ?
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.
PushManager.getSubscription() - Web APIs
var pushbutton = document.queryselector('.js-push-button'); pushbutton.disabled = false; if (!subscription) { // we aren’t subscribed to push, so set ui // to allow the user to enable push return; } // keep your server in sync with the latest subscriptionid sendsubscriptiontoserver(subscription); showcurlcommand(subscription); // set your ui to show they have subscribed for // push messages pushbutton.textcontent = 'disable push messages'; ispushenabled = true; }) .catch(function(err) { window.demo.debug.log('error during getsubscription()', err); ...
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.
RTCInboundRtpStreamStats.bytesReceived - Web APIs
the rtcinboundrtpstreamstats dictionary's bytesreceived property is an integer value which indicates the total number of bytes received so far from this synchronization source (ssrc).
RTCInboundRtpStreamStats.pliCount - Web APIs
this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media.
RTCInboundRtpStreamStats.remoteId - Web APIs
syntax var remotestatsid = rtcinboundrtpstreamstats.remoteid; value a domstring containing the id of the rtcremoteoutboundrtpstreamstats object that represents the remote peer's rtcrtpsender for the synchronization source represented by this stats object.
RTCOutboundRtpStreamStats.pliCount - Web APIs
usage notes upon receiving a pli packet, the sender may have responded by sending a full frame to the remote peer to allow it to re-synchronize with the media.
RTCOutboundRtpStreamStats.remoteId - Web APIs
syntax var remotestatsid = rtcoutboundrtpstreamstats.remoteid; value a domstring containing the id of the rtcremoteinboundrtpstreamstats object that represents the remote peer's rtcrtpreceiver for the synchronization source represented by this stats object.
RTCRemoteOutboundRtpStreamStats.remoteTimestamp - Web APIs
keep in mind that this means the clock may not be synchronized with the local clock, and that both the current time and the pace at which the clock runs may differ to some extent.
RTCRtpContributingSource.rtpTimestamp - Web APIs
this value may be useful for sequencing and synchronization purposes.
RTCRtpContributingSource - Web APIs
this value is a source-generated time value which can be used to help with sequencing and synchronization.
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.
RTCRtpReceiver - Web APIs
rtcrtpreceiver.getsynchronizationsources() returns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
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.
RTCRtpStreamStats.pliCount - Web APIs
this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media.
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 - 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: pushsubscriptionchange event - Web APIs
consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail.
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.
Using readable streams - Web APIs
also note that the previous example can be reduced by one step, as response.body is synchronous and so doesn't need the promise: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => { const reader = response.body.getreader(); reading the stream now you’ve got your reader attached, you can read data chunks out of the stream using the readablestreamdefaultreader.read() method.
SubtleCrypto.encrypt() - Web APIs
rypto.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.
WebGLRenderingContext.getContextAttributes() - Web APIs
tbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getcontextattributes(); the getcontextattributes method returns an object that describes the attributes set on this context, for example: { alpha: true, antialias: true, depth: true, failifmajorperformancecaveat: false, powerpreference: "default", premultipliedalpha: true, preservedrawingbuffer: false, stencil: false, desynchronized: false } the context attributes can be set when creating the context using the htmlcanvaselement.getcontext() method: canvas.getcontext('webgl', { antialias: false, depth: false }); see getcontext() for more information about the individual attributes.
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.
Web Animations API Concepts - Web APIs
history over a decade ago, synchronized multimedia integration language, or smil (pronounced "smile"), brought animation to svg.
Web Animations API - Web APIs
the web animations api allows for synchronizing and timing changes to the presentation of a web page, i.e.
Controlling multiple parameters with ConstantSourceNode - Web APIs
we also create gainnode2 and gainnode3, setting their values to match gainnode1, then set the value of the volume slider to the same value, so it is synchronized with the gain level it controls.
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.
Web Workers API - Web APIs
they will also allow access to push notifications and background sync apis.
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.onmozbeforepaint - Web APIs
this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code.
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.setImmediate() - Web APIs
do note that internet explorer 8 includes a synchronous version of postmessage, which means it cannot be used as a fallback.
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.setTimeout() - Web APIs
these resolve a number of issues with apps which play note-based music not being able to time or synchronize the music properly when the tab is in the background.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an idbfactory object.
WorkerGlobalScope.importScripts() - Web APIs
the importscripts() method of the workerglobalscope interface synchronously imports one or more scripts into the worker's scope.
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
="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.
XMLHttpRequest.multipart - Web APIs
all requests must be asynchronous.
XMLHttpRequest.onreadystatechange - Web APIs
warning: this should not be used with synchronous requests and must not be used from native code.
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.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 - 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...
mssitemodejumplistitemremoved - Web APIs
syntax event property object.oncandidatewindowhide = handler; addeventlistener method object.addeventlistener("mssitemodejumplistitemremoved", handler, usecapture) general info synchronous no bubbles no cancelable no note this event is raised once for every item that has been removed since the last time mssitemodeshowjumplist was called.
msthumbnailclick - Web APIs
syntax event property object.onmsthumbnailclick = handler; addeventlistener method object.addeventlistener("msthumbnailclick", handler, usecapture) general info synchronous no bubbles no cancelable no note the onmsthumbnailclick event is available only to documents that are launched from a pinned site shortcut.
An overview of accessible web applications and widgets - Accessibility
asynchronous content changes under construction.
Cognitive accessibility - Accessibility
timed content should also be avoided, with exceptions for non-interactive synchronized media and real-time events.
Perceivable - Accessibility
1.2.4 provide captions for live audio (aa) you should provide synchronized captions for all live multimedia that contains audio (e.g., video conferences, live audio broadcasts).
Using CSS transitions - CSS: Cascading Style Sheets
this is the best way to configure transitions, as it makes it easier to avoid out of sync parameters, which can be very frustrating to have to spend lots of time debugging in css.
CSS: Cascading Style Sheets
WebCSS
previously development of various parts of css specification was done synchronously, which allowed versioning of the latest recommendation.
Live streaming web audio and video - Developer guides
adaptive streaming one of the main priorities for live streaming is to keep the player synchronized with the stream: adaptive streaming is a technique for doing this in the case of low bandwidth.
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.
Date and time formats used in HTML - HTML: Hypertext Markup Language
leap years help to adjust the calendar to keep it synchronized with the actual position of the planet in its orbit.
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.
Feature-Policy - HTTP
sync-xhr controls whether the current document is allowed to make synchronous xmlhttprequest requests.
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[@@iterator]() - JavaScript
the @@iterator method is part of the iterable protocol, that defines how to synchronously iterate over a sequence of values.
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
en(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.
Lexical grammar - JavaScript
abstract boolean byte char double final float goto int long native short synchronized throws transient volatile additionally, the literals null, true, and false cannot be used as identifiers in ecmascript.
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.
Authoring MathML - MathML
"<" for tags or "$" for money amounts) you may need to synchronize the javascript converter with other javascript programs on your page.
Web audio codec guide - Web media technologies
voice recording and playback usually needs to be low-latency in order to synchronize with video tracks, or in order to avoid cross-talk or other problems.
Image file type and format guide - Web media technologies
apng is ideal for basic animations that do not need to synchronize to other activities or to a sound track, such as progress indicators, activity throbbers, and other animated sequences.
Codecs used by WebRTC - Web media technologies
of secondary importance is the need to keep the video and audio synchronized, so that the movements and any ancillary information (such as slides or a projection) are presented at the same time as the audio that corresponds.
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.
Introduction to progressive web apps - Progressive web apps (PWAs)
an app could be considered a pwa when it meets certain requirements, or implements a set of given features: works offline, is installable, is easy to synchronize, can send push notifications, etc.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
caches is a special cachestorage object available in the scope of the given service worker to enable saving data — saving to web storage won't work, because web storage is synchronous.
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.
Graphic design for responsive sites - Progressive web apps (PWAs)
you can also add links direcly into svg and can create animations using smil (synchronized multimedia intergration language).
href - SVG: Scalable Vector Graphics
WebSVGAttributehref
specifically, timeevents are dispatched and the animation element can be used as syncbase in an identical fashion to when the url refers to a valid target element.
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
290 svg animation with smil animation, firefox 4, gecko 2.0, svg, svg animation firefox 4 introduced support for animating svg using synchronized multimedia integration language (smil).
SVG animation with SMIL - SVG: Scalable Vector Graphics
firefox 4 introduced support for animating svg using synchronized multimedia integration language (smil).
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...
Introduction to using XPath in JavaScript - XPath
nue" city="washington" country="usa"/> <phonenumber>202-456-1111</phonenumber> </person> <person> <name first="tony" last="blair" /> <address street="10 downing street" city="london" country="uk"/> <phonenumber>020 7925 0918</phonenumber> </person> </people> to make the contents of the xml document available within the extension, we create an xmlhttprequest object to load the document synchronously, the variable xmldoc will contain the document as an xmldocument object against which we can use the evaluate method javascript used in the extensions xul/js documents.
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.
Basic Example - XSLT: Extensible Stylesheet Language Transformations
<xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myns:body"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunc...
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
equest = 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.