Search completed in 1.21 seconds.
Looping code - Learn web development
previous overview: building blocks next programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. here we'll look at the
loop structures available in javascript that handle such needs. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. ...
...ng repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. here we'll look at the
loop structures available in javascript that handle such needs. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand how to use
loops in javascript. keep me in the
loop loops,
loops,
loops. as well as being associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming. programming
loops are all to do with doing the same thing over and over again — which is termed iteration in programming speak. let's consider the case of a farmer that is making su...
... associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming. programming
loops are all to do with doing the same thing over and over again — which is termed iteration in programming speak. let's consider the case of a farmer that is making sure he has enough food to feed his family for the week. he might use the following
loop to achieve this: a
loop usually has one or more of the following features: a counter, which is initialized with a certain value — this is the starting point of the
loop ("start: i have no food", above). a condition, which is a true/false test to determine whether the
loop continues to run, or stops — usually when the counter reaches a certain value. this is illustrated by "have i go...
...And 45 more matches
Loops and iteration - JavaScript
« previousnext »
loops offer a quick and easy way to do something repeatedly. this chapter of the javascript guide introduces the different iteration statements available to javascript. you can think of a
loop as a computerized version of the game where you tell someone to take x steps in one direction, then y steps in another. for example, the idea "go five steps to the east" could be expressed this way as a
loop: for (let step = 0; step < 5; step++) { // runs 5 times, with values of step 0 through 4. console.log('walking east one step'); } there are many different kinds of
loops, but they all essentially do the same thing: they repeat an action some number of times. ...
...a "go five steps to the east" could be expressed this way as a
loop: for (let step = 0; step < 5; step++) { // runs 5 times, with values of step 0 through 4. console.log('walking east one step'); } there are many different kinds of
loops, but they all essentially do the same thing: they repeat an action some number of times. (note that it's possible that number could be zero!) the various
loop mechanisms offer different ways to determine the start and end points of the
loop. there are various situations that are more easily served by one type of
loop over the others. ...
... there are many different kinds of
loops, but they all essentially do the same thing: they repeat an action some number of times. (note that it's possible that number could be zero!) the various
loop mechanisms offer different ways to determine the start and end points of the
loop. there are various situations that are more easily served by one type of
loop over the others. the statements for
loops provided in javascript are: for statement do...while statement while statement labeled statement break statement continue statement for...in statement for...of statement for statement a for
loop repeats until a specified condition evaluates to false. the javascript for
loop is similar to the java and c for
loop. a for statement looks as follows: for ([initialexpression]; [conditio...
...And 18 more matches
Test your skills: Loops - Learn web development
this aim of this skill test is to assess whether you've understood our
looping code article. note: you can try out solutions for the tasks below by downloading the code, putting it in an online tool such as codepen, jsfiddle, or glitch, then working on the tasks. we didn't provide live editable versions of these tasks because of the risk of creating infinite
loops and crashing the assessment page! if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the p...
...xt contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our manipulating documents tutorial. ...
...pecific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our manipulating documents tutorial. ...
...And 6 more matches
Concurrency model and the event loop - JavaScript
this model is quite different from models in other languages like c and java. runtime concepts the following sections explain a theoretical model. modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. function foo(b) { let a = 10 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 when calling bar, a first frame is created containing bar's arguments and local variables. ...
...g only bar's call frame). when bar returns, the stack is empty. heap objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory. queue a javascript runtime uses a message queue, which is a list of messages to be processed. each message has an associated function which gets called in order to handle the message. ...
... event
loop, the runtime starts handling the messages on the queue, starting with the oldest one. to do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. as always, calling a function creates a new stack frame for that function's use. the processing of functions continues until the stack is once again empty. then, the event
loop will process the next message in the queue (if there is one). 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). "run-to-completion" each message i...
...And 3 more matches
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
the javascript warning "javascript 1.6's for-each-in
loops are deprecated; consider using es6 for-of instead" occurs when a for each (variable in obj) statement is used. message warning: javascript 1.6's for-each-in
loops are deprecated; consider using es6 for-of instead error type warning what went wrong? javascript 1.6's for each (variable in obj) statement is deprecated, and will be removed in the near future. examples object iteration for each...in has been used to iterate over the specified object values. deprecated syntax var object = { a: 10, b: 20 }; for each (var x in object) { console.log(x); // 10 // 20 } alternative standard syntax you can now use the standard for...in
loop to iterate over specified object keys, and get each value ...
...r future. examples object iteration for each...in has been used to iterate over the specified object values. ...
...{ console.log(x); // 10 // 20 } array iteration for each...in has been used to iterate over specified array elements. deprecated syntax var array = [10, 20, 30]; for each (var x in array) { console.log(x); // 10 // 20 // 30 } alternative standard syntax this is now possible with for...of (es2015)
loops as well. var array = [10, 20, 30]; for (var x of array) { console.log(x); // 10 // 20 // 30 } iterating over a null-able array for each...in does nothing if the specified value is null or undefined, but for...of will throw an exception in these cases. deprecated syntax function func(array) { for each (var x in array) { conso...
...And 2 more matches
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
a
loop is a sequence of instructions that is continually repeated until a certain condition is met in computer programming. an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number. examples for
loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run. statement 2 defines the condition needed to execute the code block. statement 3 is executed every time the code block is run. ...
... a counter has reached a prescribed number. examples for
loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run. statement 2 defines the condition needed to execute the code block. statement 3 is executed every time the code block is run. example: for(var i = 0; i < 10; i++){ console.log(i) } //this
loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the
loop (var i = 0). statement 2 sets the
loop condition (i < 10). statement 3 increases the value of i (i++) each time the code block is run. ...
...code block is run. example: for(var i = 0; i < 10; i++){ console.log(i) } //this
loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the
loop (var i = 0). statement 2 sets the
loop condition (i < 10). statement 3 increases the value of i (i++) each time the code block is run. while
loop syntax: while (condition){ execute code block } the code block will continue to
loop as long as the condition is true. ...
...ows: statement 1 sets the variable for the
loop (var i = 0). statement 2 sets the
loop condition (i < 10). statement 3 increases the value of i (i++) each time the code block is run. while
loop syntax: while (condition){ execute code block } the code block will continue to
loop as long as the condition is true. example: var i = 0; while(i < 5){ console.log(i) i++ } //this
loop will print number 0-4, will stop when condition becomes false (i >=5) for the above example, the syntax is as follows: the code block will continue to run as long as the variable (i) is less than 5. ...
AudioBufferSourceNode.loop - Web APIs
the
loop property of the audiobuffersourcenode interface is a boolean indicating if the audio asset must be replayed when the end of the audiobuffer is reached. the
loop property's default value is false. syntax var
loopingenabled = audiobuffersourcenode.
loop; audiobuffersourcenode.
loop = true | false; value a boolean which is true if
looping is enabled; otherwise, the value is false. when
looping is enabled, the sound begins playing at the time specified as the start point when start() is called. when the time specified by the
loopend property is reached, playback continues at the time specified by
loopstart example in this example, the audiocontext.decodeaudiodata function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and ...
...he
loopend property is reached, playback continues at the time specified by
loopstart example in this example, the audiocontext.decodeaudiodata function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackrate property value on the fly. when the audio is played, it
loops. you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer...
...(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.
loop = true; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); playbackcontrol.removeattribute('disabled'); } specification specification status comment ...
... working draft ...
AudioBufferSourceNode.loopStart - Web APIs
the
loopstart property of the audiobuffersourcenode interface is a floating-point value indicating, in seconds, where in the audiobuffer the restart of the play must happen. the
loopstart property's default value is 0. syntax audiobuffersourcenode.
loopstart = startoffsetinseconds; startoffsetinseconds = audiobuffersourcenode.
loopstart; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each
loop should begin during playback. this value is only used when the
loop parameter is true. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode. ...
...n seconds, into the audio buffer at which each
loop should begin during playback. this value is only used when the
loop parameter is true. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackrate,
loopstart, and
loopend properties on the fly. when the audio is played to the end, it
loops, but you can control how long the
loops last by altering
loopstart and
loopend. for example, if you set their values to 20 and 25, respectively, the audio will start to
loop between 20 and 25 seconds in to the track. for a full working example, see this code running live, or view the source. function getda...
...', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.
loop = true;
loopstartcontrol.setattribute('max', math.floor(songlength));
loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
loopstartcontrol.oninput = function() { source.
loopstart =
loopstartcontrol.value;
loopstartvalue.innerhtml =
loopstartcontrol.value; }
loope...
...ibute('max', math.floor(songlength));
loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
loopstartcontrol.oninput = function() { source.
loopstart =
loopstartcontrol.value;
loopstartvalue.innerhtml =
loopstartcontrol.value; }
loopendcontrol.oninput = function() { source.
loopend =
loopendcontrol.value;
loopendvalue.innerhtml =
loopendcontrol.value; } specifications specification status comment web audio apithe definition of '
loopstart' in that specification. working draft ...
508 Loop Detected - HTTP
the hypertext transfer protocol (http) 508
loop detected response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol. it indicates that the server terminated an operation because it encountered an infinite
loop while processing a request with "depth: infinity". this status indicates that the entire operation failed. ...
... the hypertext transfer protocol (http) 508
loop detected response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol. it indicates that the server terminated an operation because it encountered an infinite
loop while processing a request with "depth: infinity". this status indicates that the entire operation failed. ...
... in the context of the web distributed authoring and versioning (webdav) protocol. it indicates that the server terminated an operation because it encountered an infinite
loop while processing a request with "depth: infinity". this status indicates that the entire operation failed. ...
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
the javascript exception "a declaration in the head of a for-of
loop can't have an initializer" occurs when the head of a for...of
loop contains an initializer expression such as |for (var i = 0 of iterable)|. this is not allowed in for-of
loops. message syntaxerror: for-of
loop head declarations cannot have an initializer (edge) syntaxerror: a declaration in the head of a for-of
loop can't have an initializer (firefox) syntaxerror: for-of
loop variable declaration may not have an initializer. (chrome) error type syntaxerror what went wrong? the head of a for...of
loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. this is not allowed in for-of
loops. you might want a for
loop that does allow an initializer. exam...
...) syntaxerror: for-of
loop variable declaration may not have an initializer. (chrome) error type syntaxerror what went wrong? the head of a for...of
loop contains an initializer expression. that is, a variable is declared and assigned a value |for (var i = 0 of iterable)|. this is not allowed in for-of
loops. you might want a for
loop that does allow an initializer. examples invalid for-of
loop let iterable = [10, 20, 30]; for (let value = 50 of iterable) { console.log(value); } // syntaxerror: a declaration in the head of a for-of
loop can't // have an initializer valid for-of
loop you need to remove the initializer (value = 50) in the head of the for-of
loop. maybe you intended to make 50 an offset value, in that case you could add it to the
loop body, for example. let iterabl...
HTMLMediaElement.loop - Web APIs
the htmlmediaelement.
loop property reflects the
loop html attribute, which controls whether the media element should start over when it reaches the end. syntax var
loop = video.
loop; audio.
loop = true; value a boolean. example var obj = document.createelement('video'); obj.
loop = true; // true specifications specification status comment html living standardthe definition of 'htmlmediaelement.
loop' in that specification. living standard html5the definition of 'htmlmediaelement.
loop' in that specification. recommendation ...
Anatomy of a video game - Game development
this article looks at the anatomy and workflow of the average video game from a technical point of view, in terms of how the main
loop should run. it helps beginners to the modern game development arena understand what is required when building a game and how web standards like javascript lend themselves as tools. experienced game programmers who are new to web development could also benefit, too. present, accept, interpret, calculate, repeat the goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a new situation resulting from those acts. games are constantly
looping through these stages, over and over, until some end condition occurs (such as winning, losing, or exiting to go to bed). not surprising...
...end on the game. some games drive this cycle by user input. imagine that you are developing a "find the differences between these two similar pictures"-type game. these games present two images to the user; they accept their click (or touch); they interpret the input as a success, failure, pause, menu interaction, etc.; finally, they calculate an updated scene resulting from that input. the game
loop is advanced by the user's input and sleeps until they provide it. this is more of a turn-based approach that doesn't demand a constant update every frame, only when the player reacts. other games demand control over each of the smallest possible individual timeslices. the same principles as above apply with a slight twist: each frame of animation progresses the cycle and any change in user input...
...t doesn't demand a constant update every frame, only when the player reacts. other games demand control over each of the smallest possible individual timeslices. the same principles as above apply with a slight twist: each frame of animation progresses the cycle and any change in user input is caught at the first available turn. this once-per-frame model is implemented in something called a main
loop. if your game
loops based on time then this will be its authority that your simulations will adhere to. but it might not need per-frame control. your game
loop might be similar to the find the differences example and base itself on input events. it might require both input and simulated time. it might even
loop based on something else entirely. modern javascript — as described in the next sec...
...And 24 more matches
Index - Web APIs
terface provides the ability to play back audio using an audiobuffer as the source of the sound data. 115 audiobuffersourcenode.detune api, audio, audiobuffersourcenode, property, reference, web audio api, detune the detune property of the audiobuffersourcenode interface is a k-rate audioparam representing detuning of oscillation in cents. ...
...dio using an audiobuffer as the source of the sound data. 115 audiobuffersourcenode.detune api, audio, audiobuffersourcenode, property, reference, web audio api, detune the detune property of the audiobuffersourcenode interface is a k-rate audioparam representing detuning of oscillation in cents. ...
...115 audiobuffersourcenode.detune api, audio, audiobuffersourcenode, property, reference, web audio api, detune the detune property of the audiobuffersourcenode interface is a k-rate audioparam representing detuning of oscillation in cents. 116 audiobuffersourcenode.
loop api, audio, audiobuffersourcenode,
loop, media, property, reference, web audio api, sound the
loop property's default value is false. ...
...And 19 more matches
Bytecode Descriptions
utvalue for references created by super[key] in non-strict code. the receiver is this and obj is the superbase of the enclosing method. format: jof_elem, jof_propset, jof_checksloppy strictsetelemsuper stack: receiver, key, obj, val ⇒ val like jsop::setelemsuper, but for strict mode code. format: jof_elem, jof_propset, jof_checkstrict enumeration iter stack: val ⇒ iter set up a for-in
loop by pushing a propertyiteratorobject over the enumerable properties of val. implements: forin/ofheadevaluation step 6, enumerateobjectproperties. (the spec refers to an "iterator object" with a next method, but notes that it "is never directly accessible" to scripts. the object we use for this has no public methods.) if val is null or undefined, this pushes an empty iterator. the iter object pushe...
... method, but notes that it "is never directly accessible" to scripts. the object we use for this has no public methods.) if val is null or undefined, this pushes an empty iterator. the iter object pushed by this instruction must not be used or removed from the stack except by jsop::moreiter and jsop::enditer, or by error handling. ...
...ull or undefined, this pushes an empty iterator. the iter object pushed by this instruction must not be used or removed from the stack except by jsop::moreiter and jsop::enditer, or by error handling. the script's jsscript::trynotes() must mark the body of the for-in
loop, i.e. exactly those instructions that begin executing with iter on the stack, starting with the next instruction (always jsop::
loophead). ...
...And 15 more matches
Drawing graphics - Learn web development
e image, relative to the top-left corner of the canvas. parameters 8 and 9 define the width and height to draw the cut-out area of the image. in this case, we have specified the same dimensions as the original slice, but you could resize it by specifying different values. the final example should look like so: note: the finished code is available on github as 5_canvas_images.html. ...
... let's build a simple example. make another fresh copy of our canvas template (1_canvas_template.html) and open it in your code editor. add the following line to the bottom of your javascript. ...
... let's build a simple example. make another fresh copy of our canvas template (1_canvas_template.html) and open it in your code editor. add the following line to the bottom of your javascript. ...
...And 13 more matches
label - JavaScript
the labeled statement can be used with break or continue statements. it is prefixing a statement with an identifier which you can refer to. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... it is prefixing a statement with an identifier which you can refer to. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note: labeled
loops or blocks are very uncommon. usually function calls can be used instead of
loop jumps. ...
... note that javascript has no goto statement, you can only use labels with break or continue. ...
...And 13 more matches
JavaScript Daemons Management - Archive of obsolete content
)) { this.reversals = number(ncycles); } this[bsync ? "start" : "syncstart"](arguments.length > 2 ? bdirection : this.isatend() !== this.backw); }; daemon.prototype.turn = function (bsync) { /* warning: this method optionally requires the daemon.prototype.syncstart() method */ this[bsync ? ...
...guments.length > 2 ? bdirection : this.isatend() !== this.backw); }; daemon.prototype.turn = function (bsync) { /* warning: this method optionally requires the daemon.prototype.syncstart() method */ this[bsync ? ...
...vdate.gettime() : isnan(vdate) ? date.parse(vdate) : vdate; if (isfinite(ntime) && ntime > date.now()) { this.reversals = math.floor((ntime - date.now() - (this.backw ? this.index : this.length - this.index) * this.rate) / (this.length * this.rate)); this.start(this.i...
...And 7 more matches
Arrays - Learn web development
at is an array? arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like
loop through it and do the same thing to every value. maybe we've got a series of product items and their prices stored in an array, and we want to
loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom. if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the...
...e moving on. play around a bit, and see what works and what doesn't. finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. ...
...and see what works and what doesn't. finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a
loop to keep going until it has
looped through all the items in an array. so for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; for (let i = 0; i < sequence.length; i++) { console.log(sequence[i]); } you'll learn about
loops properly later on (in our
looping code article), but briefly, this code is saying: start
looping at item number 0 in the array. stop
looping at the item number equal to the length of the array. this wor...
...And 7 more matches
Object building practice - Learn web development
so when we have 25 balls on screen, no more balls appear. you can try varying the number in balls.length < 25 to get more or fewer balls on screen. depending on how much processing power yo...
...mber of balls in the array is less than 25. so when we have 25 balls on screen, no more balls appear. you can try varying the number in balls.length < 25 to get more or fewer balls on screen. ...
... how much processing power your computer/browser has, specifying several thousand balls might slow down the animation rather a lot! ...
...And 7 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
e up of a set of execution contexts, the execution context stack, a main thread, a set for any additional threads that may be created to handle workers, a task queue, and a microtask queue. other than the main thread—which some browsers share across multiple agents—each component of an agent is unique to that agent. here we look at how the runtime functions in slightly more detail. ...
... execution context stack, a main thread, a set for any additional threads that may be created to handle workers, a task queue, and a microtask queue. other than the main thread—which some browsers share across multiple agents—each component of an agent is unique to that agent. here we look at how the runtime functions in slightly more detail. event
loops each agent is driven by an event
loop, which collects any user and other events, enqueuing tasks to handle each callback. it then runs any pending javascript tasks, then any pending microtasks, then performs any needed rendering and painting before
looping again to check for pending tasks. your web site or app's code runs in the same thread, sharing the same event
loop, as the user interface of the web browser itself. this is the ma...
...ring and painting before
looping again to check for pending tasks. your web site or app's code runs in the same thread, sharing the same event
loop, as the user interface of the web browser itself. this is the main thread, and in addition to running your site's main code body, it handles receiving and dispatching user and other events, rendering and painting web content, and so forth. the event
loop, then, drives everything that happens in the browser as it pertains to the interaction with the user, but more importantly for our purposes here, it is responsible for the scheduling and execution of every piece of code that runs within its thread. ...
...And 7 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
l methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. 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. these functions are: settimeout() execute a specified block of ...
...fied amount of time (or the delay) is not the guaranteed time to execution, but rather the minimum time to execution. the callbacks you pass to these functions cannot run until the stack on the main thread is empty. as a consequence, code like settimeout(fn, 0) will execute as soon as the stack is empty, not immediately. if you execute code like settimeout(fn, 0) but then immediately after run a
loop that counts from 1 to 10 billion, your callback will be executed after a few seconds. in the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr. universe!'); }, 2000) the functions you specify don't have to b...
... time display to show the number of seconds elapsed, rather than the actual time. here's a few hints for you: you can structure and style the button markup however you like; just make sure you use semantic html, with hooks to allow you to grab the button references using javascript. you probably want to create a variable that starts at 0, then increments by one every second using a constant
loop. it is easier to create this example without using a date() object, like we've done in our version, but less accurate — you can't guarantee that the callback will fire after exactly 1000ms. a more accurate way would be to run starttime = date.now() to get a timestamp of exactly when the user clicked the start button, and then do date.now() - starttime to get the number of milliseconds after th...
...And 6 more matches
Background Tasks API - Web APIs
the cooperative scheduling of background tasks api (also referred to as the background tasks api or simply the requestidlecallback() api) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so. concepts and usage the main thread of a web browser is centered around its event
loop. this code draws any pending updates to the document currently being displayed, runs any javascript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. in addition, the event
loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. it's an extremely busy chunk of code, and your main javascript ...
...t all code that is capable of making changes to the dom is running in the main thread, since it's common for user interface changes to only be available to the main thread. because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the web and help to prevent stalls in the execution of the event
loop. ...
...ant for your code to be a good citizen of the web and help to prevent stalls in the execution of the event
loop. in the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event
loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. if you stay within the limit given, you can make the user's experience much better. ...
...And 6 more matches
for...of - JavaScript
it invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax for (variable of iterable) { statement } variable on each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. ...
...functions generating an i...
...p'); for (const paragraph of articleparagraphs) { paragraph.classlist.add('read'); } closing iterators in for...of
loops, abrupt iteration termination can be caused by break, throw or return. in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues outside of the
loop } console.log('done'); iterating over generators you can also iterate over generators, i.e. functions generating an iterable object: function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { ...
...And 6 more matches
A first splash into JavaScript - Learn web development
understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how javascript (and other programming languages) work. in subsequent articles, you'll revisit all these features in a lot more detail! note: many of the code features you'll see in javascript are the same as in other programming languages — functions,
loops, etc. the code syntax looks different, but the concepts are still largely the same. thinking like a programmer one of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. you need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what...
...ult.style.backgroundcolor = 'white'; randomnumber = math.floor(math.random() * 100) + 1; } this rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. it: puts the guesscount back down to 1. empties all the text out of the information paragraphs. we select all paragraphs inside <div class="resultparas"></div>, then
loop through each one, setting their textcontent to '' (an empty string). removes the reset button from our code. enables the form elements, and empties and focuses the text field, ready for a new guess to be entered. removes the background color from the lastresult paragraph. generates a new random number so that you are not just guessing the same number again! at this point you should have a f...
...ntered. removes the background color from the lastresult paragraph. generates a new random number so that you are not just guessing the same number again! at this point you should have a fully working (simple) game — congratulations! all we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.
loops one part of the above code that we need to take a more detailed look at is the for
loop.
loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met. to start with, go to your browser developer tools javascript console again, and enter the following: for (let i = 1 ; i < 21 ; i++) { console.log(i) } ...
...And 5 more matches
HTML parser threading
he method implementations assert which thread they are supposed to be called on. ondataavailable and onstoprequest on the main thread post runnables on to the parser thread. there runnables obtain mtokenizermutex and call dodataavailable and dostoprequest, repectively, on the parser thread. these two methods along with timerflush (discussed later) are the entry points from the parser thread event
loop into nshtml5streamparser. the runnables hold mtokenizermutex for the entire duration of the dodataavailable or dostoprequest call. mtokenizermutex protects most data structures on nshtml5streamparser from concurrent access. the runnables need to keep the nshtml5streamparser instance alive, so they have to addref it. however, if they released on the parser thread, nshtml5streamparser could be dele...
... a problem for long polling using html in an iframe e.g. for a chat app.) some tree ops hold char or prunichar arrays. those arrays are allocated when creating the tree op and delete[]d by the destructor of nshtml5treeoperation. hence, data gets copied to and from these arrays. executing tree ops when the executor flushing runnable fires on the main thread, it calls nshtml5treeopexecutor::runflush
loop(). this method returns immediately if another invocation of it is already on the call stack (nested event
loop case). the method then enters a
loop that has a bunch of return conditions (including parser termination). the
loop first flushes speculative loads (creation discussed later). if the executor is reading from a stage (i.e. the ops are coming from the parser thread), the executor moves the...
...m the parser thread), the executor moves the tree ops from the staging queue into its own queue. (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. ...
...And 5 more matches
Using the Gamepad API - Web APIs
more with the gamepad object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires. performing such checks tends to involve using the gamepad object in conjunction with an animation
loop (e.g., requestanimationframe), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads. the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned if there are no gamepads connected.) this can then be used to get the same infor...
...e() cross browser forks. var gamepadinfo = document.getelementbyid("gamepad-info"); var ball = document.getelementbyid("ball"); var start; var a = 0; var b = 0; next we use the gamepadconnected event to check for a gamepad being connected. ...
...e gamepad into our gamepad info div, and fire the game
loop() function that starts the whole ball movement process up. window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + ". it has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes."; game
loop(); }); now we use the gamepaddisconnected event to check if the gamepad is disconnected again. if so, we stop the requestanimationframe()
loop (see below) and revert the gamepad information back to what it was originally. window.addeventlistener("gamepaddisconnected", function(e) { gamepadinfo.innerhtml = "waiting for gamepad."; cancelrequestanimationframe(start); }); chrome does things d...
...And 5 more matches
Implementing controls using the Gamepad API - Game development
ndex variable is useful if we're connecting more than one controller and want to identify them to act accordingly — for example when we have a two-player game requiring two devices to be connected. querying the gamepad object beside connect() and disconnect(), there are two more methods in the gamepadapi object: update() and buttonpressed(). ...
... function() { // clear the buttons cache gamepadapi.buttonscache = []; // move the buttons status from the previous frame to the cache for(var k=0; k<gamepadapi.buttonsstatus.length; k++) { gamepadapi.buttonscache[k] = gamepadapi.buttonsstatus[k]; } // clear the buttons status gamepadapi.buttonsstatus = []; // get the gamepad object var c = gamepadapi.controller || {}; //
loop through buttons and push the pressed ones to the array var pressed = []; if(c.buttons) { for(var b=0,t=c.buttons.length; b<t; b++) { if(c.buttons[b].pressed) { pressed.push(gamepadapi.buttons[b]); } } } //
loop through axes and push their values to the array var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].t...
....length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } // assign received values gamepadapi.axesstatus = axes; gamepadapi.buttonsstatus = pressed; // return buttons for debugging purposes return pressed; }, on every frame, update() saves buttons pressed during the previous frame to the buttonscache array and takes fresh ones from the gamepadapi.controller object. then it
loops through buttons and axes to get their actual states and values. detecting button presses the buttonpressed() method is also placed in the main game
loop to listen for button presses. it takes two parameters — the button we want to listen to and the (optional) way to tell the game that holding the button is accepted. without it you'd have to release the button and press it again to have the d...
...And 4 more matches
Index - Learn web development
iscussion 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. we'll probably add to this resource as time goes on. 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, codingscripting, guide, intervals, javascript,
loops, asynchronous, requestanimationframe, setinterval, settimeout, timeouts this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. 52 general asynchronous progra...
... be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right, especially in the earlier stages of your learning journey. 89 javascript building blocks article, assessment, beginner, codingscripting, conditionals, functions, guide, introduction, javascript, landing,
loops, module, events, l10n:priority in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements,
loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. 90 build your own function...
...d then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. 93 image gallery assessment, beginner, codingscripting, conditionals, event handler, javascript, learn,
loops, events, l10n:priority now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of
loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites — a javascript-powered image gallery. 94 introduction to events article, beginner, codingscripting, event handler, guide, javascript...
...And 4 more matches
AudioBufferSourceNode - Web APIs
or when set to the value null, defines a single channel of silence (in which every sample is 0.0). audiobuffersourcenode.detune is a k-rate audioparam representing detuning of playback in cents. this value is compounded with playbackrate to determine the speed at which the sound is played. its default value is 0 (meaning no detuning), and its nominal range is -∞ to ∞. ...
...tuning of playback in cents. this value is compounded with playbackrate to determine the speed at which the sound is played. its default value is 0 (meaning no detuning), and its nominal range is -∞ to ∞. audiobuffersourcenode.
loop a boolean attribute indicating if the audio asset must be replayed when the end of the audiobuffer is reached. its default value is false. audiobuffersourcenode.
loopstart optional a floating-point value indicating the time, in seconds, at which playback of the audiobuffer must begin when
loop is true. ...
...the default value is 0. ...
...And 4 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript execution stack is empty, but before returning control to the event
loop being used by the user agent to drive the script's execution environment. this event
loop may be either the browser's main event
loop or the event
loop driving a web worker. this lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. ...
...the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. javascript promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event
loop pass is wrapping up. in order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the queuemicrotask() method is exposed on the window and worker interfaces through the windoworworkerglobalscope mixin. tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks. this is a quick, simp...
...s get added to the task queue when: a new javascript program or subprogram is executed (such as from a console, or by running the code in a <script> element) directly. an event fires, adding the event's callback function to the task queue. a timeout or interval created with settimeout() or setinterval() is reached, causing the corresponding callback to be added to the task queue. the event
loop driving your code handles these tasks one after another, in the order in which they were enqueued. only tasks which were already in the task queue when the event
loop pass began will be executed during the current iteration. the rest will have to wait until the following iteration. microtasks at first the difference between microtasks and tasks seems minor. and they are similar; both are made u...
...And 4 more matches
for await...of - JavaScript
it invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object. 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. syntax for await (variable of iterable) { statement } variable on each iteration a value of a different property is assigned to variable. variable may be declared with const, let, or var. ...
... async function* asyncgenerator() { let i = 0; while (i < 3) { yield i++; } } (async function() { for await (let num of asyncgenerator()) { console.log(num); } })(); // 0 // 1 // 2 for a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an api. this example first creates an async iterable...
...e, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaselock(); } } // fetches data from url and calculates response size using the async generator. async function getresponsesize(url) { const response = await fetch(url); // will hold the size of the response, in bytes. let responsesize = 0; // the for-await-of
loop. async iterates over each portion of the response. for await (const chunk of streamasynciterable(response.body)) { // incrementing the total response length. responsesize += chunk.length; } console.log(`response size: ${responsesize} bytes`); // expected output: "response size: 1071472" return responsesize; } getresponsesize('https://jsonplaceholder.typicode.com/photos'); iter...
...And 4 more matches
Desktop gamepad controls - Game development
er() { buttonspressed = []; if(controller.buttons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonspressed.push(b); } } } } we first reset the buttonspressed array to get it ready to store the latest info we'll write to it from the current frame. then, if the buttons are available we
loop through them; if the pressed property is set to true, then we add them to the buttonspressed array for later processing. next, we'll consider the gamepadbuttonpressedhandler() function: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press = true; } } retur...
...add them to the buttonspressed array for later processing. next, we'll consider the gamepadbuttonpressedhandler() function: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press = true; } } return press; } the function takes a button as a parameter; in the
loop it checks if the given button's number is among the currently pressed buttons available in the buttonspressed array. if it is, then the function returns true; false otherwise. next, in the draw() function we do two things — execute the gamepadupdatehandler() function to get the current state of pressed buttons on every frame, and use the gamepadbuttonpressedhandler() function to check the butt...
...mepad is connected, the information about the controller is stored in the object: connect: function(event) { gamepadapi.controller = event.gamepad; gamepadapi.active = true; }, the disconnect function removes the information from the object: disconnect: function(event) { delete gamepadapi.controller; gamepadapi.active = false; }, the update() function is executed in the update
loop of the game on every frame, so it contains the latest information on the pressed buttons: update: function() { gamepadapi.buttons.cache = []; for(var k=0; k<gamepadapi.buttons.status.length; k++) { gamepadapi.buttons.cache[k] = gamepadapi.buttons.status[k]; } gamepadapi.buttons.status = []; var c = gamepadapi.controller || {}; var pressed = []; if(c.buttons) { for(var b=0,t...
...And 3 more matches
Image gallery - Learn web development
previous overview: building blocks now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of
loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites — a javascript-powered image gallery. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript
loops, functions, conditionals, and events. starting point to get this assessment started, you should go and grab the zip file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with. alternatively, you could use a site like jsbin or glitch to do your assessm...
...e <img> and put right over the top of it (this is used to apply a darkening effect to the image via a semi-transparent background color), and a <button> that is used to control the darkening effect. it sets the width of any images inside the thumb-bar <div> (so-called "thumbnail" images) to 20%, and floats them to the left so they sit next to one another on a line. your javascript needs to:
loop through all the images, and for each one insert an <img> element inside the thumb-bar <div> that embeds that image in the page. attach an onclick handler to each <img> inside the thumb-bar <div> so that when they are clicked, the corresponding image is displayed in the displayed-img <img> element. attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied t...
...layed in the displayed-img <img> element. attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied to the full-size image. when it is clicked again, the darken effect is removed again. to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. ...
...And 3 more matches
nsIAppShell
read only. methods create() obsolete since gecko 1.9 (firefox 3) creates an application shell. void create( inout int argc, inout string argv ); parameters argc the number of parameters passed in on the command line. argv a direct reference to the parameter array. dispatchnativeevent() ...
...read only. ...
...a direct reference to the parameter array. dispatchnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code. void dispatchnativeevent( in prbool arealevent, in voidptr aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. exit() exit the handle event
loop. void exit(); parameters none. favorperformancehint() give hint to native event queue notification mechanism. if the native platform needs to tradeoff performance vs. native event starvation this hint tells the native dispatch code which to favor. the default is to prevent native event starvation. calls to this function may be nested. when the number of calls that pass pr_true is subtracted from...
...And 3 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
there. control structures javascript has a similar set of control structures to other languages in the c family. ...
...uctures javascript has a similar set of control structures to other languages in the c family. conditional statements are supported by if and else; you can chain them together if you like: var name = 'kittens'; if (name == 'puppies') { name += ' woof'; } else if (name == 'kittens') { name += ' meow'; } else { name += '!'; } name == 'kittens meow'; javascript has while
loops and do-while
loops. the first is good for basic
looping; the second for
loops where you wish to ensure that the body of the
loop is executed at least once: while (true) { // an infinite
loop! } var input; do { input = get_input(); } while (inputisnotvalid(input)); javascript's for
loop is the same as that in c and java: it lets you provide the control information for your
loop on a single line. for (var i...
... of the
loop is executed at least once: while (true) { // an infinite
loop! } var input; do { input = get_input(); } while (inputisnotvalid(input)); javascript's for
loop is the same as that in c and java: it lets you provide the control information for your
loop on a single line. for (var i = 0; i < 5; i++) { // will execute 5 times } javascript also contains two other prominent for
loops: for...of for (let value of array) { // do something with value } and for...in: for (let property in object) { // do something with object property } the && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. this is useful for checking for null objects before accessing their attributes: var name = o && o.getn...
...And 3 more matches
for...in - JavaScript
a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax for (variable in object) statement variable a different property name is assigned to variable on each iteration. object object whose non-symbol enumerable properties are iterated over. ...
...n each iteration. object object whose non-symbol enumerable properties are iterated over. description a for...in
loop only iterates over enumerable, non-symbol properties. objects created from built–in constructors like array and object have inherited non–enumerable properties from object.prototype and string.prototype, such as string's indexof() method or object's tostring() method. the
loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). ...
...ype and string.prototype, such as string's indexof() method or object's tostring() method. the
loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). deleted, added, or modified properties a for...in
loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). if a property is modified in one iteration and then visited at a later time, its value in the
loop is its value at that later time. a property that is deleted before it has been visited will not b...
...And 3 more matches
for - JavaScript
typically used to initialize a counter variable. this expression may optionally declare new variables with var or let keywords. ...
...typically used to initialize a counter variable. this expression may optionally declare new variables with var or let keywords. ...
...interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax for ([initialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the
loop begins. typically used to initialize a counter variable. this expression may optionally declare new variables with var or let keywords. variables declared with var are not local to the
loop, i.e. they are in the same scope the for
loop is in. variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated before each l...
...And 3 more matches
Building up a basic demo with Babylon.js - Game development
le creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. ...
...es just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering
loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var render
loop = function () { scene.render(); }; engine.runrender
loop(render
loop); we're using the engine's runrender
loop() method to execute the render
loop() function repeatedly on every frame — the
loop will continue to render indefinitely until told to stop. creating a camera now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects...
...now: this works, but it is a bit boring. in a game something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them. animation we already used position and rotation to adjust the position of the shapes; we could also scale them. ...
...And 2 more matches
How to embed the JavaScript engine
threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
... * 1024); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...And 2 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
sists of master controls, which allow us to play/stop the sequencer, and adjust the bpm (beats per minute) to speed up or slow down the "music". there are four different sounds, or voices, which can be played. each voice has four buttons, which represent four beats in one bar of music. when they are enabled the note will sound. when the instrument plays, it will move across this set of beats and
loop the bar. each voice also has local controls, which allow you to manipulate the effects or parameters particular to each technique we are using to create those voices. the techniques we are using are: name of voice technique associated web audio api feature "sweep" oscillator, periodic wave oscillatornode, periodicwave "pulse" multiple oscillators ...
...this would be very handy for more complex instruments, or gaming. we can now use setupsample() like so: setupsample() .then((sample) => { // sample is our buffered file // ... }); when the sample is ready to play, the program sets up the ui so it is ready to go. playing the sample let's create a playsample() function in a similar m...
...s consistent, and things do not slip out of time. audiocontext object instances have a currenttime property, which allows us to retrieve the number of seconds after we first created the context. this is what we shall use for timing within our step sequencer — it's extremely accurate, returning a float value accurate to about 15 decimal places. we could schedule our voices to play within a for
loop, however the biggest problem with this is updating whilst it is playing, and we've already implemented ui controls to do so. also, it would be really nice to consider an instrument-wide bpm control. the best way to get our voices to play on the beat is to create a scheduling system, whereby we look ahead at when the notes are going to play and push them into a queue. we can start them at a precis...
...And 2 more matches
InternalError: too much recursion - JavaScript
ssing a base case. message error: out of stack space (edge) internalerror: too much recursion (firefox) rangeerror: maximum call stack size exceeded (chrome) error type internalerror. what went wrong? a function that calls itself is called a recursive function. once a condition is met, the function stops calling itself. this is called a base case. in some ways, recursion is analogous to a
loop. ...
...efox) rangeerror: maximum call stack size exceeded (chrome) error type internalerror. what went wrong? ...
... case. in some ways, recursion is analogous to a
loop. both execute the same code multiple times, and both require a condition (to avoid an infinite
loop, or rather, infinite recursion in this case). when there are too many function calls, or a function is missing a base case, javascript will throw this error. examples this recursive function runs 10 times, as per the exit condition. function
loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do stuff
loop(x + 1); // the recursive call }
loop(0); setting this condition to an extremely high value, won't work: function
loop(x) { if (x >= 1000000000000) return; // do stuff
loop(x + 1); }
loop(0); // internalerror: too much recursion this recursive function is missing a base case. as there is no exit c...
...And 2 more matches
Array.prototype[@@iterator]() - JavaScript
l, that defines how to synchronously iterate over a sequence of values. the initial value of the @@iterator property is the same function object as the initial value of the values() property. syntax arr[symbol.iterator]() return value the initial value given by the values() iterator. by default, using arr[symbol.iterator] will return the values() function. ...
...iterator]() return value the initial value given by the values() iterator. by default, using arr[symbol.iterator] will return the values() function. ...
...alue given by the values() iterator. by default, using arr[symbol.iterator] will return the values() function. ...
...And 2 more matches
Index - Game development
ary 1 game development apps, game development, gamedev, games, html5 games, javascript games, web gaming is one of the most popular computer activities. new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. 2 anatomy of a video game games, javascript, main
loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game. the correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. the concern is mostly with switching to another option. fortunately, i do not have any experience with this, but i have heard it is an excruciating game of whack-a-mole. 3 ...
...ving your canvas/webgl games a crisp pixel art look, even on high definition monitors. 28 efficient animation for web games animation, games, javascript this article covers techniques and advice for creating efficient animation for web games, with a slant towards supporting lower end devices such as mobile phones. we touch on css transitions and css animations, and javascript
loops involving window.requestanimationframe. 29 implementing controls using the gamepad api controls, gamepad api, gamepads, games, javascript, controllers the gamepad api is very easy to develop with. now it's easier than ever to deliver a console-like experience to the browser without the need for any plugins. you can play the full version of the hungry fridge game directly in ...
...on into the game — first we'll look at the walls. 45 build the brick field 2d, beginner, canvas, games, javascript, phaser, tutorial building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a
loop. 46 buttons 2d, beginner, buttons, canvas, games, javascript, phaser, tutorial instead of starting the game right away we can leave that decision to the player by adding a start button they can press. let's investigate how to do that. 47 collision detection 2d, beginner, canvas, games, javascript, phaser, tutorial, collision detection now onto the next ch...
...nd let it reach the bottom edge of the screen, then it's game over. 66 mouse controls beginner, canvas, controls, games, javascript, tutorial, mouse the game itself is actually finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. 67 move the ball 2d, beginner, canvas, games, javascript,
loop, tutorial, movement you already know how to draw a ball from working through the previous article, so now let's make it move. technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies. 68 paddle and keyboard control...
Audio for Web games - Game development
usical experience. you may want music to change depending on whether you are trying to build suspense or encourage the player in some way. music is an important part of the gaming experience and depending on the type of game you are making you may wish to invest significant effort into getting it right. one way you can make your music soundtrack more dynamic is by splitting it up into component
loops or tracks. this is often the way that musicians compose music anyway, and the web audio api is extremely good at keeping these parts in sync. once you have the various tracks that make up your piece you can bring tracks in and out as appropriate. you can also apply filters or effects to music. is your character in a cave? increase the echo. maybe you have underwater scenes, during which you cou...
...ks in and out as appropriate. you can also apply filters or effects to music. is your character in a cave? increase the echo. maybe you have underwater scenes, during which you could apply a filter that muffles the sound. let's look at some web audio api techniques for dynamically adjusting music from its base tracks. 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. loading synchronously might mean parts of your music are ready earlier and you can start playing them while others load. either way you may want to synchronize tracks or
loops. the web audio api contains the notion of an internal clock that starts ticking the moment you create an audi...
...ich is our offset. ...
...button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } playtrack(track); playbutton.dataset.playing = true; }) }) }) note: you can see this demo in action here and view the source code here. in the context of your game world you may have
loops and samples that are played in different circumstances, and it can be useful to be able to synchronize with other tracks for a more seamless experience. note: this example does not wait for the beat to end before introducing the next piece; we could do this if we knew the bpm (beats per minute) of the tracks. you may find that the introduction of a new track sounds more natural if it comes i...
Build the brick field - Game development
e gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson09.html. building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a
loop. defining new variables first, let's define the needed variables — add the following below your previous variable definitions: var bricks; var newbrick; var brickinfo; the bricks variable will be used to create a group, newbrick will be a new object added to the group on every iteration of the
loop, and brickinfo will store all the data we need. rendering the brick image next, let's load...
...columns of bricks we will see on screen, the top and left offset (the location on the canvas where we shall start to draw the bricks) and the padding between each row and column of bricks. now, let's start creating the bricks themselves — add an empty group first to contain the bricks, by adding the following line at the bottom of the initbricks() function: bricks = game.add.group(); we can
loop through the rows and columns to create new brick on each iteration — add the following nested
loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group. now we need to add so...
...mns to create new brick on each iteration — add the following nested
loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group. now we need to add some code inside the nested
loop stucture to draw each brick. fill in the contents as shown below: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { var brickx = 0; var bricky = 0; newbrick = game.add.sprite(brickx, bricky, 'brick'); game.physics.enable(newbrick, phaser.physics.arcade); newbrick.body.immovable = true; newbrick.anchor.set(0.5); ...
...the newly created brick is enabled for the arcade physics engine, it's body is set to be immovable (so it won't move when hit by the ball), and we're also setting the anchor to be in the middle and adding the brick to the group. the problem currently is that we're painting all the bricks in one place, at coord...
Dynamic behavior in Svelte: working with variables and props - Learn web development
ty values, and even add a new todo object. observe how the numbers in the message are updated appropriately. dynamically generating the todos from the data at the moment, our displayed todo items are all static. we want to iterate over each item in our todos array and render the markup for each task, so let's do that now. html doesn't have a way of expressing logic — like conditionals and
loops. svelte does. in this case we use the {#each...} directive to iterate over the todos array. the second parameter, if provided, will contain the index of the current item. also, a key expression can be provided, which will uniquely identify each item. svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify ...
... simplified version to get an idea of how it works: <ul> {#each todos as todo, index (todo.id)} <li> <input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id}) </li> {:else} nothing to do here! {/each} </ul> go back to the app; you'll see something like this: now we've seen that this is working, let's generate a complete todo item with each
loop of the {#each} directive, and inside embed the information from the todos array: id, name, and completed. replace your existing <ul> block with the following: <!-- todos --> <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading"> {#each todos as todo (todo.id)} <li class="todo"> <div class="stack-small"> <div class="c-cb"> <input type="checkb...
...=== 'all'} — when the javascript expression passed between curly braces evaluates to a truthy value, the aria-pressed attribute will be added to the button. whenever we click on a button we update the filter variable by issuing on:click={()=> filter = 'all'}. read on to find out how svelte reactivity will take care of the rest. now we just need to use the helper function in the {#each}
loop; update it like this: ... <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading"> {#each filtertodos(filter, todos) as todo (todo.id)} ... after analyzing our code, svelte detects that our filtertodos() function depends on the variables filter and todos. and, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies chan...
...odo (todo.id)} ... after analyzing our code, svelte detects that our filtertodos() function depends on the variables filter and todos. and, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies change the dom will be updated accordingly. so whenever filter or todos changes, the filtertodos() function will be re-evaluated and the items inside the
loop will be updated. tip: reactivity can be tricky sometimes. svelte recognizes filter as a dependency because we are referencing it in the filtertodos(filter, todo) expression. filter is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this — filtertodos(todo). this would work, but now svelte has no way to find out that {#each fi...
Rendering a list of Vue components - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. ...
...and line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn how to
loop through an array of data and render it in multiple components. rendering lists with v-for to be an effective to-do list, we need to be able to render multiple to-do items. to do that, vue has a special directive, v-for. this is a built-in vue directive that lets us include a
loop inside of our template, repeating the rendering of a template feature for each item in an array. we'll use thi...
...lse }, { label: 'create a vue project with the cli', done: true }, { label: 'have fun', done: true }, { label: 'create a to-do list', done: false } ] }; } }; now that we have a list of items, we can use the v-for directive to display them. directives are applied to elements like other attributes. in case of v-for, you use a special syntax similar to a for...in
loop in javascript — v-for="item in items" — where items is the array you want to iterate over, and item is a reference to the current element in the array. v-for attaches to the element you want to repeat, and renders that element and its children. in this case, we want to display an <li> element for every to-do item inside our todoitems array. then we want to pass the data from each to-do item...
... </li> </ul> </div> </template> when you look at your rendered site, it should look the same, but our refactor now means that our id is being taken from the data inside app.vue and passed into todoitem as a prop, just like everything else, so things are now more logical and consistent. summary and that brings us to the end of another article. we now have sample data in place, and a
loop that takes each bit of data and renders it inside a todoitem in our app. what we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. we'll get to these in the next a...
HTTP Cache
e always desirable. see context keying details for more information. code examples tbd opening an entry creating a new entry recreating an already open entry implementation threading the cache api is fully thread-safe. the cache is using a single background thread where any io operations like opening, reading, writing and erasing happen. also memory pool management, eviction, visiting
loops happen on this thread. the thread supports several priority levels. dispatching to a level with a lower number is executed sooner then dispatching to higher number layers; also any
loop on lower levels yields to higher levels so that scheduled deletion of 1000 files will not block opening cache entries. open_priority: except opening priority cache files also file dooming happens here to prev...
... == ready: oncacheentrycheck with the entry is invoked on the first opener in fifo - on the caller thread if demanded result == recheck_after_write_finished: opener is left in the fifo with a flag recheckafterwrite such openers are skipped until the output stream on the entry is closed, then oncacheentrycheck is re-invoked on them note: here is a potential for endless
looping when recheck_after_write_finished is abused result == entry_needs_revalidation: state = revalidating, this prevents invocation of any callback until cacheentry::setvalid is called continue as in state entry_wanted (just bellow) result == entry_wanted: consumer reference ++ (dropped back when the consumer releases the entry) oncacheentryavai...
...e is invoked on the opener with anew = false and the entry opener is removed from the fifo result == entry_not_wanted: oncacheentryavailable is invoked on the opener with null for the entry opener is removed from the fifo state == writing or revalidating: do nothing and exit any other value of state is unexpected here (assertion failure)
loop this process while there are openers in the fifo cacheentry::onfileready (entry atomic): load result == failure or the file has not been found on disk (is new): state = empty otherwise: state = ready since the cache file has been found and is usable containing meta data and data of the entry call to cacheentry::invokecallbacks cacheentry::onhandleclosed (entry atomic): called when any...
...te memory caching of frequently used metadata (a.k.a. disk cache memory pool) this is a description of this feature status that is currently only a patch in bug 986179. current behavior is simpler and causes a serious memory consumption regression (bug 975367). for the disk cache entries we keep some of the most recent and most used cache entries' meta data in memory for immediate zero-thread-
loop opening. the default size of this meta data memory pool is only 250kb and is controlled by a new browser.cache.disk.metadata_memory_limit preference. when the limit is exceeded, we purge (throw away) first expired and then least used entries to free up memory again. only cacheentry objects that are already loaded and filled with data and having the 'consumer reference == 0' (bug 942835) can be ...
Profiling with the Firefox Profiler
annotated with "[tab]" are in the web content (aka "child") processes. tip: long-running tasks in the parent process will block all input or drawing with the browser ui (aka "ui jank") whereas long-running tasks in the content process will block interactivity with the page but still allowing the user to pan and zoom around thanks to apz. tracing markers red: these indicate that the event
loop is being unresponsive. note that high priority events such as vsync are not included here. also note that this indicates what would have happened had there been an event waiting and not necessarily that there was an event pending for that long. black: these indicate synchronous ipc calls. ranges ranges of time can be zoomed in on by clicking and dragging anywhere in the tracing marker or th...
...at are taking the most time; then you can figure out how to optimize them. common performance bugs in firefox inefficient code that is on the reflow or restyle paths is often to blame for jank. so is code that is run often in the parent process or in parts of the codebase that apply to many users. ...
... optimize them. common performance bugs in firefox inefficient code that is on the reflow or restyle paths is often to blame for jank. so is code that is run often in the parent process or in parts of the codebase that apply to many users. 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. a presshell:flush means that we are either recomputing styles or recomputing layout. these sorts of flushes should be avoided if possible, as they can be quite expensive. keep your eyes out for flushes like this that are blocking the main thread for a long time. if you notice these things happening in a
loop, that's a bug to be fixed, since we're likely "layout thrashing". some more tips and a...
...amespace", "name"). these add raii helpers, which are used by the profiler to track entries/exits of the annotated functions. for this to be effective, you need to liberally use auto_profiler_label throughout the code. see geckoprofiler.h for more variations like auto_profiler_label_dynamic. because of the non-zero overhead of the instrumentation, the sample label shouldn't be placed inside hot
loops. a profile reporting that a large portion is spent in "unknown" code indicates that the area being executed doesn't have any sample labels. as we focus on using this tool and add additional sample labels coverage should improve. sharing, saving and loading profiles after capturing and viewing a profile you will see "share..." and "save as file..." buttons in the top-right of the window. shar...
Enc Dec MAC Output Public Key as CSR
slot, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and wrapped keys and * public key * unwrap the wrapped keys *
loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secst...
...ate request * generate a symmetric aes key as a session object. * generate a second key to use for macing, also a session object. ...
...!infilename) { usage(progname); } /* * read cert request from a file and extract public key * generates an aes encryption key, session object * generates a mac key, session object * wraps each of those keys with rsa public key * write wrapped keys and public key into intermediate header file * encryption and macing
loop * destroy session keys * close files */ rv = encryptfile(slot, infilename, certreqfilename, headerfilename, encryptedfilename, noisefilename, &pwdata, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encryptfile : failed\n"); return secfailure; } break; ca...
... break; case decrypt: /* validate command for decrypt */ if (!infilename && !outfilename) { usage(progname); } /* * reads intermediate header including public key and wrapped keys * finds rsa private key corresponding to the public key * unwraps two keys, creating session key objects * decryption and mac checking
loop to write to output file * destroy session keys * close files */ rv = decryptfile(slot, outfilename, headerfilename, encryptedfilename, &pwdata, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decryptfile : failed\n"); return secfailure; } break; } cleanup: if (slo...
Index
38, jsnewenumerateop is the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are called in order. the properties each op adds to the properties vector are added to the set of values the for-in
loop will iterate over. all of this is nonstandard. 127 jsnewresolveop jsapi reference, obsolete, spidermonkey like jsresolveop, but flags provide contextual information about the property access. 128 jsobject jsapi reference, spidermonkey objects are made up of the following parts: 129 jsobjectop jsapi reference, obsolete, spidermonkey th...
... and js_removeroot to manage global roots temporarily. 256 js_enumerate jsapi reference, spidermonkey js_enumerate gets the ids of all own properties of the specified object, obj, that have the jsprop_enumerate attribute. (the term own property refers to a property that is not inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in
loop, which converts all property ids to strings and also enumerates inherited properties. 257 js_enumeratediagnosticmemoryregions jsapi reference, reference, référence(2), spidermonkey js_enumeratediagnosticmemoryregions enumerates memory regions that contain diagnostic information intended to be included in crash report minidumps. 258 js_enumerateresolvedstandardcla...
...class ids into ida, or into a new jsidarray if ida is null. return the augmented array on success, null on failure with ida (if it was non-null on entry) destroyed. 259 js_enumeratestandardclasses jsapi reference, reference, référence(2), spidermonkey the global object's class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in
loops any classes not yet resolved lazily. 260 js_errorfromexception jsapi reference, reference, référence(2), spidermonkey if obj is an exception object, the exception will have (or be able to lazily create) an error report struct, and js_errorfromexception will return the address of that struct. otherwise, it returns nullptr. the lifetime of the error report struct that might ...
...inobject jsapi reference, reference, référence(2), spidermonkey js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]]. 410 js_newpropertyiterator jsapi reference, obsolete, spidermonkey create an object to iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in
loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) 411 js_newregexpobject jsapi reference, reference, référence(2), spidermonkey js_newregexpobject and js_newucregexpobject create a new regexp instance. the flags from the built-in regexp constructor propert...
Plug-in Basics - Plugins
n a document, it attempts to find and display the file represented by the data and src attributes, respectively. the height and width attributes of the object element determine the size of the embedded plug-in in the html page. for example, this object element calls a plug-in that displays video: <object data="newave.avi" type="video/avi" width="320" height="200" autostart="true"
loop="true"> </object> a hidden plug-in is a type of embedded plug-in that is not drawn on the screen when it is invoked. it is created by using the hidden attribute of the embed element. here's an example: <embed src="audiplay.aiff" type="audio/x-aiff" hidden="true"> note: whether a plug-in is windowed or windowless is not meaningful if the plug-in is invoked with the hidden attribute. you ca...
...ion between the html page and the plug-in code. the browser ignores these nonstandard attributes when parsing the html, but it passes all attributes to the plug-in, allowing the plug-in to examine the list for any private attributes that could modify its behavior. ...
...butes to the plug-in, allowing the plug-in to examine the list for any private attributes that could modify its behavior. for example, a plug-in that displays video could have private attributes that determine whether to start the plug-in automatically or
loop the video automatically on playback, as in the following embed element: <embed src="myavi.avi" width="100" height="125" autostart="true"
loop="true"> with this embed element, gecko passes the values to the plug-in, using the arg parameters of the npp_new call that creates the plug-in instance. argc = 5 argn = {"src", "width", "height", "autostart", "
loop"} argv = {"movie.avi", "100", "125", "true", "true"} gecko interprets the attributes as follows: src: load the data file and determine the mime type of the data. width and h...
...parameters of the npp_new call that creates the plug-in instance. argc = 5 argn = {"src", "width", "height", "autostart", "
loop"} argv = {"movie.avi", "100", "125", "true", "true"} gecko interprets the attributes as follows: src: load the data file and determine the mime type of the data. width and height: set the area of the page handled by the plug-in to 100 by 125 pixels. autostart and
loop: ignore these private attributes and pass them along to the plug-in with the rest of the attributes. the plug-in must scan its list of attributes to determine whether it should automatically start the video and
loop it on playback. note that with an object element, param values are also sent in this array after the attributes, separated by a param entry. plug-in references the mozilla plug-...
Rendering and the WebXR frame animation callback - Web APIs
once your webxr environment has been set up and an xrsession created to represent an ongoing xr environment session, you need to provide frames of the scene to the xr device for rendering. this article covers the process of driving the frames of the xr scene to the device in the rendering
loop, using the xrsession to obtain an xrframe object representing each frame, which is then used to prepare the framebuffer for delivery to the xr device. before you can render the virtual environment, you need to establish a webxr session by creating an xrsession using the navigator.xr.requestsession() method; you also need to associate the session with a framebuffer and perform other setup tasks. these setup tasks are described in the article setting up and shutting down a webxr session. preparing the r...
...osition and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace(). then the first animation frame is scheduled by calling the xrsession method requestanimationframe(), providing a callback function, mydrawframe(), whose job is to render the frame. note that this code doesn't have a
loop! instead, the frame rendering code—in this case, a function named mydrawframe()—is responsible for scheduling time to draw another frame by once again calling requestanimationframe(). refresh rate and frame rate assuming you've called the xrsession method requestanimationframe() since the last time the screen refreshed, the browser will call your frame renderer callback every time it's read...
...d. the next frame drawn will be frame 4 instead. this is another reason the timestamp passed into your render callback is useful. by configuring the scene based on time rather than frame number, you can ensure your rendered frames match what's expected instead of falling behind. when a frame is dropped, the contents of the affected display area simply don't change for that pass through the frame
loop. for that reason, the occasional dropped frame isn't usually particularly noticeable, but if it starts to happen a lot—especially if several frames are dropped in a very short span of time—it can become jarring or even leave your display unusable. fortunately, you can easily compute how much time you're allowed to use between frames as 1/refreshrate seconds. that is, by dividing 1 by the dis...
...d height into gl.viewport(). finally, we call our method mydrawsceneintoview() to actually use webgl to render the scene. into this, we pass the xrview representing the eye we're drawing for (in order to perform perspective mapping and the like) and deltatime, so the scene drawing code can accurately represent the elapsed time when determining the positions of objects moving over time. when the
loop that's iterating over the views ends, every image required to represent the scene to the viewer has been rendered, and upon return, the framebuffer makes its way through the gpu and eventually to the xr device's display or displays. since we called requestanimationframe() at thee top of the function, our callback will be invoked once again when it's time to render the next frame of the scene's an...
Using the Web Animations API - Web APIs
moving it to javascript now let’s try creating the same animation with the web animations api. representing keyframes the first thing we need is to create a keyframe object corresponding to ...
... { 0% { color: #000; transform: rotate(0) translate3d(-50%, -50%, 0); } 30% { color: #431236; } 100% { color: #000; transform: rotate(360deg) translate3d(-50%, -50%, 0); } } this changes alice’s color and her transform’s rotation over 3 seconds at a constant (linear) rate and
loops infinitely. in the @keyframes block we can see that 30% of the way through each
loop (about .9 seconds in), alice’s color changes from black to a deep burgundy then back again by the end of the
loop. moving it to javascript now let’s try creating the same animation with the web animations api. representing keyframes the first thing we need is to create a keyframe object corresponding to our css @keyframes block: var alicetumbling = [ { transform: 'rotate(0) translate3d...
...each object represents a key from the original css. however, unlike css, the web animations api doesn’t need to explicitly be told the percentages along the animation for each key to appear at. it will automatically divide the animation into equal parts based on the number of keys you give it. this means that a keyframe object with three keys will play the middle key 50% of the way through each
loop of the animation unless told otherwise. when we want to explicitly set a key’s offset from the other keys, we can specify an offset directly in the object, separated from the declaration with a comma. in the above example, to make sure that alice’s color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3. currently, there should be at least two keyframes specified (...
...hem slow down? getting information out of animations imagine other ways we could use playbackrate, such as improving accessibility for users with vestibular disorders by letting them slow down animations across an entire site. ...
Visualizations with Web Audio API - Web APIs
to set up the buffer: analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); next, we clear the canvas of what had been drawn on it before to get ready for the new visualization display: canvasctx.clearrect(0, 0, width, height); we now define the draw() function: function draw() { in here, we use requestanimationframe() to keep
looping the drawing function once it has been started: var drawvisual = requestanimationframe(draw); next, we grab the time domain data and copy it into our array analyser.getbytetimedomaindata(dataarray); next, fill the canvas with a solid colour to start canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); set a line width and stroke colour for the wave we will ...
...tx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); determine the width of each segment of the line to be drawn by dividing the canvas width by the array length (equal to the frequencybincount, as defined earlier on), then define an x variable to define the position to move to for drawing each segment of the line. ...
...we have set the fft size to be much smaller; this is so that each bar in the graph is big enough to actually look like a bar rather than a thin strand. analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); next, we start our draw() function off, again setting up a
loop with requestanimationframe() so that the displayed data keeps updating, and clearing the display with each animation frame. function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); now we set our barwidth to be equal to the canvas width divide...
...ncy range. we don't want to display loads of empty bars, therefore we simply shift the ones that will display regularly at a noticeable height across so they fill the canvas display. we also set a barheight variable, and an x variable to record how far across the screen to draw the current bar. var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; as before, we now start a for
loop and cycle through each value in the dataarray. for each one, we make the barheight equal to the array value, set a fill colour based on the barheight (taller bars are brighter), and draw a bar at x pixels across the canvas, which is barwidth wide and barheight/2 tall (we eventually decided to cut each bar in half so they would all fit on the canvas better.) the one value that needs explaining is...
Redirections in HTTP - HTTP
not even a transmitted page. html redirects (<meta>) execute if there weren't any http redirects. javascript redirects execute last, and only if javascript is enabled. when possible, use http redirects and don't add <meta> element redirects. if someone changes the http redirects but forgets to change the html redirects, the redirects will no longer be identical, which could cause an infinite
loop or other nightmares. use cases there are numerous use cases for redirects, but as performance is impacted with every redirect, their use should be kept to a minimum. domain aliasing ideally, there is one location, and therefore one url, for each resource. but there are reasons for alternative names for a resource: expanding the reach of your site a common case is when a site resides at ww...
...er { listen 80; server_name example.com; return 301 $scheme://www.example.com$request_uri; } to apply a redirect to a directory or only certain pages, use the rewrite directive: rewrite ^/images/(.*)$ https://images.example.com/$1 redirect; rewrite ^/images/(.*)$ https://images.example.com/$1 permanent; iis in iis, you use the <httpredirect> element to configure redirections. redirection
loops redirection
loops happen when additional redirections follow the one that has already been followed. in other words, there is a
loop that will never be finished and no page will ever be found. most of the time this is a server problem, and if the server cannot detect it, it will send back a 500 internal server error. if you encounter such an error soon after modifying a server configuration, t...
...when additional redirections follow the one that has already been followed. in other words, there is a
loop that will never be finished and no page will ever be found. most of the time this is a server problem, and if the server cannot detect it, it will send back a 500 internal server error. if you encounter such an error soon after modifying a server configuration, this is likely a redirection
loop. sometimes, the server won't detect it: a redirection
loop can spread over several servers which each don't have the full picture. in this case, browsers will detect it and display an error message. ...
...
loop. sometimes, the server won't detect it: a redirection
loop can spread over several servers which each don't have the full picture. in this case, browsers will detect it and display an error message. firefox displays: firefox has detected that the server is redirecting the request for this address in a way that will never complete. …while chrome displays: this webpage has a redirect
loop in both cases, the user can't do much (unless a corruption is happening on their side, like a mismatch of cache or cookies). it is important to avoid redirection
loops, as they completely break the user experience. ...
Closures - JavaScript
sum4(d){ // local scope return a + b + c + d + e; } } } } var s = sum(1); var s1 = s(2); var s2 = s1(3); var s3 = s2(4); console.log(s3) //log 20 in the example above, there's a series of nested functions, all of which have access to the outer functions' scope. in this context, we can say that closures have access to all outer function scopes. creating closures in
loops: a common mistake prior to the introduction of the let keyword in ecmascript 2015, a common problem with closures occurred when you created them inside a
loop. to demonstrate, consider the following example code. <p id="help">helpful notes will appear here</p> <p>e-mail: <input type="text" id="email" name="email"></p> <p>name: <input type="text" id="name" name="name"></p> <p>age: <input type="...
...d': 'age', 'help': 'your age (you must be over 16)'} ]; for (var i = 0; i < helptext.length; i++) { var item = helptext[i]; document.getelementbyid(item.id).onfocus = function() { showhelp(item.help); } } } setuphelp(); try running the code in jsfiddle. the helptext array defines three helpful hints, each associated with the id of an input field in the document. the
loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method. if you try this code out, you'll see that it doesn't work as expected. no matter what field you focus on, the message about your age will be displayed. the reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured...
...associated help method. if you try this code out, you'll see that it doesn't work as expected. no matter what field you focus on, the message about your age will be displayed. the reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setuphelp function's scope. ...
...aptured environment from the setuphelp function's scope. three closures have been created by the
loop, but each one shares the same single lexical environment, which has a variable with changing values (item). this is because the variable item is declared with var and thus has function scope due to hoisting. the value of item.help is determined when the onfocus callbacks are executed. because the
loop has already run its course by that time, the item variable object (shared by all three closures) has been left pointing to the last entry in the helptext list. one solution in this case is to use more closures: in particular, to use a function factory as described earlier: function showhelp(help) { document.getelementbyid('help').innerhtml = help; } function makehelpcallback(help) { return...
Functions - JavaScript
unction's name arguments.callee an in-scope variable that refers to the function for example, consider the following function definition: var foo = function bar() { // statements go here } within the function body, the following are all equivalent: bar() arguments.callee() foo() a function that calls itself is called a recursive function. in some ways, recursion is analogous to a
loop. ...
...nsider the following function definition: var foo = function bar() { // statements go here } within the function body, the following are all equivalent: bar() arguments.callee() foo() a function that calls itself is called a recursive function. in some ways, recursion is analogous to a
loop. both execute the same code multiple times, and both require a condition (to avoid an infinite
loop, or rather, infinite recursion in this case). for example, the following
loop... ...
...ing are all equivalent: bar() arguments.callee() foo() a function that calls itself is called a recursive function. in some ways, recursion is analogous to a
loop. both execute the same code multiple times, and both require a condition (to avoid an infinite
loop, or rather, infinite recursion in this case). for example, the following
loop... var x = 0; while (x < 10) { // "x < 10" is the
loop condition // do stuff x++; } ...can be converted into a recursive function declaration, followed by a call to that function: function
loop(x) { if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)") return; // do stuff
loop(x + 1); // the recursive call }
loop(0); however, some algorithms cannot be simple iterative
loops. for example, getting all the node...
... it is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack. in fact, recursion itself uses a stack: the function stack. ...
Indexed collections - JavaScript
ray(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number. otherwise, an array with a single element (the provided value) will be created. calling arr.length will return arraylength, but the array doesn't contain any elements. a for...in
loop will not find any property on the array. in addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object: let obj = {} // ... obj.prop = [element0, element1, ..., elementn] // or let obj = {prop: [element0, element1, ...., elementn]} if you wish to initialize an array with a single element, and the element happens to be a numb...
... the foreach() method provides another way of iterating over an array: let colors = ['red', 'green', 'blue'] colors.foreach(function(color) { console.log(color) }) // red // green // blue alternatively, you can shorten the code for the foreach parameter with es2015 arrow functions: let colors = ['red', 'green', 'blue'] colors.foreach(color => console.log(color)) // re...
... // blue alternatively, you can shorten the code for the foreach parameter with es2015 arrow functions: let colors = ['red', 'green', 'blue'] colors.foreach(color => console.log(color)) // red // green // blue the function passed to foreach is executed once for every item in the array, with the array item passed as the argument to the function. unassigned values are not iterated in a foreach
loop. note that the elements of an array that are omitted when the array is defined are not listed when iterating by foreach, but are listed when undefined has been manually assigned to the element: let array = ['first', 'second', , 'fourth'] array.foreach(function(element) { console.log(element) }) // first // second // fourth if (array[2] === undefined) { console.log('array[2] is undefined')...
... array methods the array object has the following methods: concat() joins two or more arrays and returns a new array. let myarray = new array('1', '2', '3') myarray = myarray.concat('a', 'b', 'c') // myarray is now ["1", "2", "3", "a", "b", "c"] join(delimiter = ',') joins all elements of an array into a string. let mya...
Iteration protocols - JavaScript
tions to ecmascript 2015, iteration protocols aren't new built-ins or syntax, but protocols. these protocols can be implemented by any object by simply following some conventions. there are two protocols: the iterable protocol and the iterator protocol. the iterable protocol the iterable protocol allows javascript objects to define or customize their iteration behavior, such as what values are
looped over in a for...of construct. some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not. in order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant sym...
..., meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that returns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of
loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. note that when this zero-argument function is called, it is invoked as a method on the iterable object. therefore inside of the function, the this keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration. this func...
... ]).get(myobj); // "b" new set([1, 2, 3]).has(3); // true new set('123').has('2'); // true new weakset(function* () { yield {} yield myobj yield {} }()).has(myobj); // true see also promise.all(iterable) promise.race(iterable) array.from(iterable) syntaxes expecting iterables some statements and expressions expect iterables, for example the for...of
loops, the spread operator), yield*, and destructuring assignment: for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" console.log([...'abc']); // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } console.log(gen().next()); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); console.log(a); // "a" non-well-formed iterabl...
... console.log(gen.next().value); // '0' console.log(gen.next().value); // '1' console.log(gen.next().value); // '2' // ... with es2015 class class simpleclass { constructor(data) { this.data = data; } [symbol.iterator]() { // use a new index for each iterator. this makes multiple // iterations over the iterable safe for non-trivial cases, // such as use of break or nested
looping over the same iterable. let index = 0; return { next: () => { if (index < this.data.length) { return {value: this.data[index++], done: false} } else { return {done: true} } } } } } const simple = new simpleclass([1,2,3,4,5]); for (const val of simple) { console.log(val); // '1' '2' '3' '4' '5' } is a generator object ...
break - JavaScript
description the break statement includes an optional label that allows the program to break out of a labeled statement. the break statement needs to be nested within the referenced label. ...
...he statement following the terminated statement. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax break [label]; label optional identifier associated with the label of the statement. if the statement is not a
loop or switch, this is required. description the break statement includes an optional label that allows the program to break out of a labeled statement. the break statement needs to be nested within the referenced label. the labeled statement can be any block statement; it does not have to be preceded by a
loop statement. a break statement, with or without a following label, cannot be used within...
...includes an optional label that allows the program to break out of a labeled statement. the break statement needs to be nested within the referenced label. the labeled statement can be any block statement; it does not have to be preceded by a
loop statement. a break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current
loop, switch, or label statement that the break statement is intended to break out of. examples break in while
loop the following function has a break statement that terminates the while
loop when i is 3, and then returns the value 3 * x. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i * x; } break in labeled blocks the fol...
... statement is within block_1 but references block_2. a break statement must always be nested within any label it references. block_1: { console.log('1'); break block_2; // syntaxerror: label not found } block_2: { console.log('2'); } break within functions syntaxerrors are also generated in the following code examples which use break statements within functions that are nested within a
loop, or labeled block that the break statements are intended to break out of. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break; })(); } i += 1; } return i * x; } testbreak(1); // syntaxerror: illegal break statement block_1: { console.log('1'); ( function() { break block_1; // syntaxerror: undefined label 'block_1...
do...while - JavaScript
}) to group those statements. ...
...e example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax do statement while (condition); statement a statement that is executed at least once and is re-executed each time the condition evaluates to true. ...
...thub.com/mdn/interactive-examples and send us a pull request. syntax do statement while (condition); statement a statement that is executed at least once and is re-executed each time the condition evaluates to true. to execute multiple statements within the
loop, use a block statement ({ ... }) to group those statements. condition an expression evaluated after each pass through the
loop. if condition evaluates to true, the statement is re-executed. when condition evaluates to false, control passes to the statement following the do...while. examples using do...while in the following example, the do...while
loop iterates at least once and reiterates until i is no longer less than 5. var result = ''; var i = 0; do { i += 1; result += i + ' '; } while (i > 0 && i < 5); //...
..., the statement is re-executed. when condition evaluates to false, control passes to the statement following the do...while. examples using do...while in the following example, the do...while
loop iterates at least once and reiterates until i is no longer less than 5. var result = ''; var i = 0; do { i += 1; result += i + ' '; } while (i > 0 && i < 5); // despite i == 0 this will still
loop as it starts off without the test console.log(result); specifications specification ecmascript (ecma-262)the definition of 'do-while statement' in that specification. ...
while - JavaScript
statement an optional statement that is executed as long as the condition evaluates to true. ...
... true. the condition is evaluated before executing the statement. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax while (condition) statement condition an expression evaluated before each pass through the
loop. if this condition evaluates to true, statement is executed. when condition evaluates to false, execution continues with the statement after the while
loop. statement an optional statement that is executed as long as the condition evaluates to true. to execute multiple statements within the
loop, use a block statement ({ ... }) to group those statements. note: use the break statement to stop...
...f this condition evaluates to true, statement is executed. when condition evaluates to false, execution continues with the statement after the while
loop. statement an optional statement that is executed as long as the condition evaluates to true. to execute multiple statements within the
loop, use a block statement ({ ... }) to group those statements. note: use the break statement to stop a
loop before condition evaluates to true. examples using while the following while
loop iterates as long as n is less than three. var n = 0; var x = 0; while (n < 3) { n++; x += n; } each iteration, the
loop increments n and adds it to x. therefore, x and n take on the following values: after the first pass: n = 1 and x = 1 after the second pass: n = 2 and x = 3 after the third pass: n ...
... as long as n is less than three. var n = 0; var x = 0; while (n < 3) { n++; x += n; } each iteration, the
loop increments n and adds it to x. therefore, x and n take on the following values: after the first pass: n = 1 and x = 1 after the second pass: n = 2 and x = 3 after the third pass: n = 3 and x = 6 after completing the third pass, the condition n < 3 is no longer true, so the
loop terminates. specifications specification ecmascript (ecma-262)the definition of 'while statement' in that specification. ...
Build the brick field - Game development
eat as it means the game is finally feeling more like a game. however, it will quickly get boring if all you do is bounce the ball off the walls and the paddle. what a breakout game really needs is some bricks to destroy with the ball, and this is what we'll create now! setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested
loop that works through a two-dimensional array. first however we need to set up some variables to define information about the bricks such as their width and height, rows and columns, etc. add the following lines to your code below the variables which you have previously declared in your program. var brickrowcount = 3; var brickcolumncount = 5; var brickwidth = 75; var brickheight = 20; var brickpad...
...olumns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen. add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will
loop through the rows and columns and create the new bricks. note that the brick objects will also be used for collision detection purposes later. brick drawing logic now let's create a function to
loop through all the bricks in the array and draw them on the screen. our code might look like this: function drawbricks() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcou...
...look like this: function drawbricks() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { bricks[c][r].x = 0; bricks[c][r].y = 0; ctx.beginpath(); ctx.rect(0, 0, brickwidth, brickheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } } } again, we're
looping through the rows and columns to set the x and y position of each brick, and we're also painting a brick on the canvas — size brickwidth x brickheight — with each
loop iteration. the problem is that we're painting them all in one place, at coordinates (0,0). what we need to do is include some calculations that will work out the x and y position of each brick for each
loop iteration: var br...
2D maze game with device orientation - Game development
this.leveldata = [ [ { x: 96, y: 224, t: 'w' } ], [ { x: 72, y: 320, t: 'w' }, { x: 200, y: 320, t: 'h' }, { x: 72, y: 150, t: 'w' } ], // ... ]; every array element holds a collection of blocks with an x and y position and t value for each. ...
...item.t); } newlevel.setall('body.immovable', true); newlevel.visible = false; this.levels.push(newlevel); } first, add.group() is used to create a new group of items. then the arcade body type is set for that group to enable physics calculations. the newlevel.create method creates new items in the group with starting left and top positions, and its own image. if you don't want to
loop through the list of items again to add a property to every single one explicitly, you can use setall on a group to apply it to all the items in that group. the objects are stored in the this.levels array, which is by default invisible. to load specific levels, we make sure the previous levels are hidden, and show the current one: showlevel: function(level) { var lvl = level | this.level; ...
...his.game.add.text(15, 15, "time: "+this.timer, this.fontbig); this.totaltimetext = this.game.add.text(120, 30, "total time: "+this.totaltimer, this.fontsmall); we’re defining the top and left positions of the text, the content that will be shown and the styling applied to the text. we have this printed out on the screen, but it would be good to update the values every second: this.time.events.
loop(phaser.timer.second, this.updatecounter, this); this
loop, also in the create function, will execute the updatecounter function every single second from the beginning of the game, so we can apply the changes accordingly. this is how the complete updatecounter function looks: updatecounter: function() { this.timer++; this.timertext.settext("time: "+this.timer); this.totaltimetext.set...
Practical positioning examples - Learn web development
tabs[i].classname = ''; } tab.classname = 'active'; for(i = 0; i < panels.length; i++) { panels[i].classname = ''; } panels[tabpos].classname = 'active-panel'; } } this code does the following: first we save a reference to all the tabs and all the panels in two variables called tabs and panels, so we can easily do things to them later on. then we use a for
loop to cycle through all the tabs and run a function called settabhandler() on each one, which sets up the functionality that should occur when each one is clicked on. when run, the function is passed a reference to the particular tab it is being run for, and an index number i that indentifies the tab's position in the tabs array. in the settabhandler() function, the tab has an onclick event handler...
...h one, which sets up the functionality that should occur when each one is clicked on. when run, the function is passed a reference to the particular tab it is being run for, and an index number i that indentifies the tab's position in the tabs array. ...
...t on it, so that when the tab is clicked, the following occurs: a for
loop is used to cycle through all the tabs and remove any classes that are present on them. a class of active is set on the tab that was clicked on — remember from earlier that this class has an associated rule in the css that sets the same color and background-color on the tab as the panels are styled with. a for
loop is used to cycle through all the panels and remove any classes that are present on them. a class of active-panel is set on the panel that corresponds to the tab that was clicked on — remember from earlier that this class has an associated rule in the css that sets its z-index to 1, making it appear over the top of the other panels. that's it for the first example. keep your code open,...
Functions — reusable blocks of code - Learn web development
been using functions all the way through the course so far; we've just not been talking about them very much. now is the time, however, for us to start talking about functions explicitly, and really exploring their syntax. pretty much anytime you make use of a javascript structure that features a pair of parentheses — () — and you're not using a common built-in language structure like a for
loop, while or do...while
loop, or if...else statement, you are making use of a function. built-in browser functions we've made use of functions built in to the browser a lot in this course. every time we manipulated a text string, for example: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); console.log(newstring); // the replace() string function takes a source s...
...e built-in functions, as well as the built-in objects and their corresponding methods here. you've also seen a lot of custom functions in the course so far — functions defined in your code, not inside the browser. anytime you saw a custom name with parentheses straight after it, you were using a custom function. in our random-canvas-circles.html example (see also the full source code) from our
loops article, we included a custom draw() function that looked like this: function draw() { ctx.clearrect(0,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } this function draws 100 random circles inside a <canvas> element. every time we want...
...is again in your javascript console: a(); b(); this time the a() and b() calls will both return an annoying referenceerror: variable name is not defined error — this is because the output() calls and the variables they are trying to print are not in the same function scopes — the variables are effectively invisible to those function calls. note: the same scoping rules do not apply to
loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing! take care not to get these confused. note: the referenceerror: "x" is not defined error is one of the most common you'll encounter. if you get this error and you are sure that you have defined the variable in question, check what scope it is in. functions inside fun...
JavaScript building blocks - Learn web development
you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. ...
...ogramming language, code needs to make decisions and carry out actions accordingly depending on different inputs. for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article we'll explore how conditional structures work in javascript.
looping code sometimes you need a task done more than once in a row. for example, looking through a list of names. in programming,
loops perform this job very well. here we will look at
loop structures in javascript. functions — reusable blocks of code another essential concept in coding is functions. functions allow you to store a piece of code that does a single task inside a defined block, and...
...on by displaying an information box. in this final article we will discuss some important concepts surrounding events, and look at how they work in browsers. assessments the following assessment will test your understanding of the javascript basics covered in the guides above. image gallery now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of
loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites — a javascript-powered image gallery. ...
Third-party APIs - Learn web development
next, we set the articles variable to equal json.response.docs — this is the array holding all the objects that represent the ...
... next, we set the articles variable to equal json.response.docs — this is the array holding all the objects that represent the articles returned by the search. ...
...that we want to use to display each news story, insert the right contents into each one, and then insert them into the dom at the appropriate places. to work out which properties in the article objects contained the right data to show, we consulted the article search api reference (see nytimes apis). most of these operations are fairly obvious, but a few are worth calling out: we used a for
loop (for(var j = 0; j < current.keywords.length; j++) { ... } ) to
loop through all the keywords associated with each article, and insert each one inside its own <span>, inside a <p>. this was done to make it easy to style each one. we used an if() block (if(current.multimedia.length > 0) { ... }) to check whether each article has any images associated with it (some stories don't.) we display the ...
Server-side web frameworks - Learn web development
.: jinja2 (python), handlebars (javascript), moustache (javascript), etc. the code snippet below shows how this works. continuing the "youngest team" example from the previous section, the html template is passed a list variable called youngest_teams by the view. inside the html skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for
loop. on each iteration the template displays the team's team_name value in a list item. #best/templates/best/index.html <!doctype html> <html lang="en"> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>no teams are available.</p> {% endif %} </body> </html> how to select a web framewo...
...e access and support for users and sessions are provided through independent libraries). there are many excellent independent components, but sometimes it can be hard to work out which is the best for a particular purpose! many popular server-side and full stack frameworks (comprising both server and client-side frameworks) are based on express, including feathers, itemsapi, keystonejs, kraken,
loopback, mean, and sails. a lot of high profile companies use express, including: uber, accenture, ibm, etc. (a list is provided here). deno (javascript) deno is a simple, modern, and secure javascript/typescript runtime and framework built on top of chrome v8 and rust. deno is powered by tokio — a rust-based asynchronous runtime which lets it serve web pages faster. it also has internal suppor...
...d here). deno (javascript) deno is a simple, modern, and secure javascript/typescript runtime and framework built on top of chrome v8 and rust. deno is powered by tokio — a rust-based asynchronous runtime which lets it serve web pages faster. it also has internal support for webassembly, which enables the compilation of binary code for use on the client-side. deno aims to fill in some of the
loop-holes in node.js by providing a mechanism that naturally maintains better security. deno's features include: security by default. deno modules restrict permissions to file, network, or environment access unless explicitly allowed. typescript support out-of-the-box. first-class await mechanism. built-in testing facility and code formatter (deno fmt) (javascript) browser compatibility: deno...
PR_InitializeNetAddr
ss structure is allocated by, and remains the responsibility of, the calling client. syntax #include <prnetdb.h> prstatus pr_initializenetaddr( prnetaddrvalue val, pruint16 port, prnetaddr *addr); parameters the function has the following parameters: val the value to be assigned to the ip address portion of the network address. this must be pr_ipaddrnull, pr_ipaddrany, or pr_ipaddr
loopback. port the port number to be assigned in the network address structure. the value is specified in host byte order. addr a pointer to the prnetaddr structure to be manipulated. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occur, for example, if the value of val is not within the ranges defined by prnetaddrv...
...the reason for the failure by calling pr_geterror. description pr_initializenetaddr allows the assignment of special network address values and the port number, while also setting the state that indicates the version of the address being used. the special network address values are identified by the enum prnetaddrvalue: typedef enum prnetaddrvalue{ pr_ipaddrnull, pr_ipaddrany, pr_ipaddr
loopback } prnetaddrvalue; the enum has the following enumerators: pr_ipaddrnull do not overwrite the ip address. this allows the caller to change the network address' port number assignment without affecting the host address. pr_ipaddrany assign logical pr_inaddr_any to ip address. this wildcard value is typically used to establish a socket on which to listen for incoming connection requests.
...taddrvalue; the enum has the following enumerators: pr_ipaddrnull do not overwrite the ip address. this allows the caller to change the network address' port number assignment without affecting the host address. pr_ipaddrany assign logical pr_inaddr_any to ip address. this wildcard value is typically used to establish a socket on which to listen for incoming connection requests. pr_ipaddr
loopback assign logical pr_inaddr_
loopback. a client can use this value to connect to itself without knowing the host's network address. ...
Index
a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with
looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl str...
... if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap ove...
...rintable interpretation of the data, use the -h option, or, if you are looking at an ssl connection, the -s option. you will notice that the page you retrieved looks incomplete in the browser. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on
looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output connected to interzone.mcom.com:443 -->; [ alloclen = 66 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 39 (0x27) sid-length...
NSS tools : ssltab
instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with
looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-enco...
.... the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercep...
...tput a basic, printable interpretation of the data, use the -h option, or, if you are looking at an ssl connection, the -s option. you will notice that the page you retrieved looks incomplete in the browser. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on
looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output connected to interzone.mcom.com:443 -->; [ alloclen = 66 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 39 (0x27) sid-length = 0 (0x00) challenge-length = 16 (0x10) cipher-suites = { (0x01...
NSS tools : ssltap
instead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with
looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-enco...
.... the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and examples you can use the ssl debugging tool to intercep...
...tput a basic, printable interpretation of the data, use the -h option, or, if you are looking at an ssl connection, the -s option. you will notice that the page you retrieved looks incomplete in the browser. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on
looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output connected to interzone.mcom.com:443 -->; [ alloclen = 66 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 39 (0x27) sid-length = 0 (0x00) challenge-length = 16 (0x10) cipher-suites = { (0x01...
NSS Tools ssltap
nstead of outputting raw data, the command interprets each record as a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with
looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-e...
...ory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: http 80 https 443 smtp 25 ftp 21 imap 143 imaps 993 (imap over ssl) nntp 119 nntps 563 (nntp over ssl) examples you can use the ssl debugging tool to in...
...put a basic, printable interpretation of the data, use the -h option, or, if you are looking at an ssl connection, the -s option. you will notice that the page you retrieved looks incomplete in the browser. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on
looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 the s and x options in this example turn on ssl parsing and show undecoded values in hex/ascii format. the output is routed to a text file. command ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output output connected to interzone.mcom.com:443--> [a...
NSS tools : ssltap
a numbered line of hex values, followed by the same data as ascii characters. the two parts are separated by a vertical bar. nonprinting characters are replaced by dots. -f turn on fancy printing. output is printed in colored html. data sent from the client to the server is in blue; the server's reply is in red. when used with
looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl str...
... if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap ove...
...rintable interpretation of the data, use the -h option, or, if you are looking at an ssl connection, the -s option. you will notice that the page you retrieved looks incomplete in the browser. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on
looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 $ ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output connected to interzone.mcom.com:443 -->; [ alloclen = 66 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 39 (0x27) sid-length...
Tracing JIT
trace recorder, of type tracerecorder. it then passes control back to the spidermonkey interpreter. the interpreter continues interpreting bytecode, but with an important difference: each bytecode it interprets is also sent to the trace monitor and recorded in the monitor's trace recorder. recording mode is temporary -- ideally it only lasts as long as it takes to record a single iteration of a
loop in the interpreter -- and can end in a number of ways. all transitions out of recording mode eventually involve returning to monitoring mode: if the recorder is asked to record a bytecode that it cannot, for various low-level reasons, faithfully record, the recorder may choose to abort the recording. aborting a recording is always an option in tracemonkey, and on abort the monitor simply disca...
...monitor also keeps track of how many times it has attempted to record a trace starting at each pc value, so if a particular pc causes too many aborted recordings, the monitor blacklists the pc and will not attempt recording it any longer. if the recorder completes recording at a backward branch back to the initial pc value that triggered recording mode, it is said to have successfully closed the
loop. ...
...eps track of how many times it has attempted to record a trace starting at each pc value, so if a particular pc causes too many aborted recordings, the monitor blacklists the pc and will not attempt recording it any longer. if the recorder completes recording at a backward branch back to the initial pc value that triggered recording mode, it is said to have successfully closed the
loop. a closed
loop is passed through the nanojit assembler and thereby compiled to native machine code. the associated fragment is placed in the monitor's fragment table and the monitor returns to monitoring mode, with a high likelihood of immediately transitioning to executing mode on the next bytecode interpreted. the compiled fragment of code returned to the monitor on successful
loop-close is called a trace. i...
SpiderMonkey Internals
n the compiler) to jump to the appropriate chunk of code for the current instruction. a js-to-js function call pushes a javascript stack frame without growing the c stack. but since js-to-c-to-js call stacks are common, the interpreter is reentrant. some spidermonkey bytecode operations have many special cases, depending on the type of their arguments. common cases are inlined in the interpreter
loop, breaking any abstractions that stand in the way. so optimizations such as dense arrays and the property cache are, alas, not transparently tucked away in the jsarray.* and jsobj.* files. both guest-star in jsinterp.cpp (to thunderous applause from firefox users). all state associated with an interpreter instance is passed through formal parameters to the interpreter entry point; most implicit s...
...s, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set. line number to pc and back mapping functions. the line-to-pc direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return the pc of a for-
loop update part, if given the line number of the
loop body's closing brace. any line after the last one in a script or function maps to a pc one byte beyond the last bytecode in the script. an example, from perfect.js: function perfect(n) { print("the perfect numbers up to " + n + " are:"); // we build sumofdivisors[i] to hold a string expression for // the sum of the divisors of i, excluding ...
...sumofdivisors; print("that's all."); } the line number to pc and back mappings can be tested using the js program with the following script: load("perfect.js"); print(perfect); dis(perfect); print(); for (var ln = 0; ln <= 40; ln++) { var pc = line2pc(perfect, ln); var ln2 = pc2line(perfect, pc); print("\tline " + ln + " => pc " + pc + " => line " + ln2); } the result of the for
loop over lines 0 to 40 inclusive is: line 0 => pc 0 => line 16 line 1 => pc 0 => line 16 line 2 => pc 0 => line 16 line 3 => pc 0 => line 16 line 4 => pc 0 => line 16 line 5 => pc 0 => line 16 line 6 => pc 0 => line 16 line 7 => pc 0 => line 16 line 8 => pc 0 => line 16 line 9 => pc 0 => line 16 line 10 => pc 0 => line 16 line 11 => pc 0 => line 16 line 12 => pc 0 => line 16 line 13 => pc 0 => line ...
Index
5, this preference is no longer used. 908 nsisimpleenumerator interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference called to retrieve the next element in the enumerator. the "next" element is the first element upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a
loop to iterate over the elements in the enumerator. 909 getnext documentation is now located at nsisimpleenumerator.getnext(). 910 hasmoreelements documentation is now located at nsisimpleenumerator.hasmoreelements(). 911 nsismsdatabaseservice interfaces, mobile, websms implemented by: @mozilla.org/sms/smsdatabaseservice;1. to create an...
...m api reference, xpcom interface reference implemented by: @mozilla.org/intl/stringbundle;1. to access this service, use: 927 nsistringenumerator called to retrieve the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a
loop to iterate over the strings in the enumerator. 928 nsistructuredclonecontainer interfaces, interfaces:scriptable, needscontent you can copy an object into an nsistructuredclonecontainer using initfromvariant() or initfrombase64(). it is an error to initialize an nsistructuredclonecontainer more than once. 929 nsistylesheetservice interfaces, interfaces:scriptab...
...ming it's encoded in acharset and return the converted string in utf-8. 1040 nsiutf8stringenumerator interfaces, interfaces:scriptable, xpcom interface reference, strings returns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which returns pr_true. this method is generally called within a
loop to iterate over the strings in the enumerator. 1041 nsiuuidgenerator add-ons, extensions, interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference implemented by @mozilla.org/uuid-generator; as a service: 1042 nsiupdate interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference retrieves a patc...
nsIWebBrowserChrome
embedding/browser/webbrowser/nsiwebbrowserchrome.idlscriptable corresponds to the top-level, outermost window containing an embedded gecko web browser. inherits from: nsisupports last changed in gecko 0.9.6 method overview void destroybrowserwindow(); void exitmodalevent
loop(in nsresult astatus); boolean iswindowmodal(); void setstatus(in unsigned long statustype, in wstring status); void showasmodal(); void sizebrowserto(in long acx, in long acy); attributes attribute type description chromeflags unsigned long the chrome flags for this browser chrome. the implementation should reflect the value of this attribute by hiding or showing its chrome appropriately. webbrowser nsiwebb...
...e_openas_chrome 2147483648 represent special cases. chrome_all 4094 represent special cases. chrome_remote_window 1048576 whether this window should use remote (out-of-process) tabs. methods destroybrowserwindow() asks the implementer to destroy the window associated with this webbrowser object. void destroybrowserwindow(); parameters none. exitmodalevent
loop() exit a modal event
loop if we're in one. the implementation should also exit out of the
loop if the window is destroyed. void exitmodalevent
loop( in nsresult astatus ); parameters astatus the result code to return from showasmodal(). iswindowmodal() is the window modal (that is, currently executing a modal
loop)? boolean iswindowmodal(); parameters none. return value true if it's ...
...signed long statustype, in wstring status ); parameters statustype indicates what is setting the text. status status string. null is an acceptable value meaning no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. return value note: the function error code returned by this corresponds to the status value specified in exitmodalevent
loop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx new width of the browser. acy new height of the browser. ...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
ourcenode = new audiobuffersourcenode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: buffer: an instance of audiobuffer to be played. detune: a value in cents to modulate the speed of audio stream rendering. its nominal range is (-∞ to +∞). the default is 0.
loop: a boolean indicating whether the audio should play in a
loop. the default is false. if the
loop is dynamically modified during playback, the new value will take effect on the next processing block of audio.
loopend: an optional value, in seconds, where
looping should end if the
loop attribute is true. the default is 0. its value is exclusive to the content of the
loop. the sample frames, compr...
...n indicating whether the audio should play in a
loop. the default is false. if the
loop is dynamically modified during playback, the new value will take effect on the next processing block of audio.
loopend: an optional value, in seconds, where
looping should end if the
loop attribute is true. the default is 0. its value is exclusive to the content of the
loop. the sample frames, comprising the
loop, run from the values
loopstart to
loopend-(1/samplerate). it's sensible to set this to a value between 0 and the duration of the buffer. if
loopend is less than 0,
looping will end at 0. if
loopend is greater than the duration of the buffer,
looping will end at the end of the buffer. this attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's samp...
.... if
loopend is less than 0,
looping will end at 0. if
loopend is greater than the duration of the buffer,
looping will end at the end of the buffer. this attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. thus, its behavior is independent of the value of the playbackrate parameter.
loopstart: an optional value in seconds, where
looping should begin if the
loop attribute is true. the default is 0. it's sensible to set this to a value between 0 and the duration of the buffer. if
loopstart is less than 0,
looping will begin at 0. if
loopstart is greater than the duration of the buffer,
looping will begin at the end of the buffer. this attribute is converted to an exact sample frame...
Applying styles and colors - Web APIs
perty. the valid strings you can enter should, according to the specification, be css <color> values. each of the following examples describe the same color. // these all set the fillstyle to 'orange' ctx.fillstyle = 'orange'; ctx.fillstyle = '#ffa500'; ctx.fillstyle = 'rgb(255, 165, 0)'; ctx.fillstyle = 'rgba(255, 165, 0, 1)'; a fillstyle example in this example, we once again use two for
loops to draw a grid of rectangles, each in a different color. the resulting image should look something like the screenshot. there is nothing too spectacular happening here. we use the two variables i and j to generate a unique rgb color for each square, and only modify the red and green values. the blue channel has a fixed value. by modifying the channels, you can generate all kinds of palettes. by ...
...sparency value of this particular color. the valid range is again between 0.0 (fully transparent) and 1.0 (fully opaque). a globalalpha example in this example, we'll draw a background of four different colored squares. on top of these, we'll draw a set of semi-transparent circles. the globalalpha property is set at 0.2 which will be used for all shapes from that point on. every step in the for
loop draws a set of circles with an increasing radius. the final result is a radial gradient. by overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. by increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image. function draw() { var ctx = docu...
...nts uses a fully transparent color. if you want to have a nice transition from this to the previous color stop, both colors should be equal. this isn't very obvious from the code because it uses two different css color methods as a demonstration, but in the first gradient #019f62 = rgba(1,159,98,1). screenshotlive sample patterns in one of the examples on the previous page, we used a series of
loops to create a pattern of images. there is, however, a much simpler method: the createpattern() method. createpattern(image, type) creates and returns a new canvas pattern object. image is a canvasimagesource (that is, an htmlimageelement, another canvas, a <video> element, or the like. type is a string indicating how to use the image. the type specifies how to use the image in order to creat...
Basic animations - Web APIs
. restore the canvas state if you've saved the state, restore it before drawing a new frame. controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions. in normal circumstances, we only see these results appear on the canvas when the script finishes executing. for instance, it isn't possible to do an animation from within a for
loop. that means we need a way to execute our drawing functions over a period of time. there are two ways to control an animation like this. scheduled updates first there's the window.setinterval(), window.settimeout(), and window.requestanimationframe() functions, which can be used to call a specific function over a set period of time. setinterval(function, delay) starts repeatedly executing t...
...e the window.requestanimationframe() method to control the animation. the requestanimationframe method provides a smoother and more efficient way for animating by calling the animation frame when the system is ready to paint the frame. the number of callbacks is usually 60 times per second and may be reduced to a lower rate when running in background tabs. for more information about the animation
loop, especially for games, see the article anatomy of a video game in our game development zone. an animated solar system this example animates a small model of our solar system. var sun = new image(); var moon = new image(); var earth = new image(); function init() { sun.src = 'https://mdn.mozillademos.org/files/1456/canvas_sun.png'; moon.src = 'https://mdn.mozillademos.org/files/1443/canvas...
...we're using an image of yosemite national park we took from wikipedia, but you could use any image that's larger than the canvas. var img = new image(); // user variables - customize these to change the image being scrolled, its // direction, and the speed. img.src = 'https://mdn.mozillademos.org/files/4553/capitan_meadows,_yo...
Using images - Web APIs
mage() method adds two new parameters and lets us place scaled images on the canvas. drawimage(image, x, y, width, height) this adds the width and height parameters, which indicate the size to which to scale the image when drawing it onto the canvas. example: tiling an image in this example, we'll use an image as a wallpaper and repeat it several times on the canvas. this is done simply by
looping and placing the scaled images at different positions. in the code below, the first for
loop iterates over the rows. the second for
loop iterates over the columns. the image is scaled to one third of its original size, which is 50x38 pixels. note: images can become blurry when scaling up or grainy if they're scaled down too much. scaling is probably best not done if you've got some text in it...
...ble containing several images. when the page is loaded, a <canvas> element is inserted for each image and a frame is drawn around it. in this case, every image has a fixed width and height, as does the frame that's drawn around them. you could enhance the script so that it uses the image's width and height to make the frame fit perfectly around it. the code below should be self-explanatory. we
loop through the document.images container and add new canvas elements accordingly. probably the only thing to note, for those not so familiar with the dom, is the use of the node.insertbefore method. insertbefore() is a method of the parent node (a table cell) of the element (the image) before which we want to insert our new node (the canvas element). <html> <body onload="draw();"> <table> ...
...59.png" width="132" height="150"> </body> </html> and here's some css to make things look nice: body { background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4f191a; margin: 10px; } img { display: none; } table { margin: 0 auto; } td { padding: 15px; } tying it all together is the javascript to draw our framed images: function draw() { //
loop through all images for (var i = 0; i < document.images.length; i++) { // don't add a canvas for the frame image if (document.images[i].getattribute('id') != 'frame') { // create canvas element canvas = document.createelement('canvas'); canvas.setattribute('width', 132); canvas.setattribute('height', 150); // insert before the image document.images[...
EventTarget.addEventListener() - Web APIs
are discarded. they do not cause the eventlistener to be called twice, and they do not need to be removed manually with the removeeventlistener() method. note, however that when using an anonymous function as the handler, such listeners will not be identical, because anonymous functions are not identical even if defined using the same unchanging source-code simply called repeatedly, even if in a
loop. however, repeatedly defining the same named function in such cases can be more problematic. (see memory issues, below.) the value of "this" within the handler it is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements. if attaching a handler function to an element using addeventlistener(), the value ...
...mentsbytagname('*'); // case 1 for(let i=0 ; i < els.length; i++){ els[i].addeventlistener("click", function(e){/*do something*/}, false); } // case 2 function processevent(e){ /* do something */ } for(let i=0 ; i < els.length; i++){ els[i].addeventlistener("click", processevent, false); } in the first case above, a new (anonymous) handler function is created with each iteration of the
loop. ...
... actually, regarding memory consumption, the lack of keeping a function reference is not the real issue; rather it is the lack of keeping a static function reference. ...
Using IndexedDB - Web APIs
to span all object stores, but don't do it because the spec says an empty array should generate an invalidaccesserror. if you don't specify anything for the second argument, you get a read-only transaction. since you want to write to it here you need to pass the "readwrite" flag. now that you have a transaction you need to understand its lifetime. transactions are tied very closely to the event
loop. ...
...spec says an empty array should generate an invalidaccesserror. if you don't specify anything for the second argument, you get a read-only transaction. since you want to write to it here you need to pass the "readwrite" flag. now that you have a transaction you need to understand its lifetime. transactions are tied very closely to the event
loop. ...
...as long as there are pending requests the transaction remains active. transaction lifetimes are really very simple but it might take a little time to get used to. a few more examples will help, too. if you start seeing transaction_inactive_err error codes then you've messed something up. ...
WebXR performance guide - Web APIs
yourself needing to make adjustments or compromises to optimize the performance of your webxr application to be as usable as possible on the broadest assortment of target devices. in this guide, we'll examine a variety of suggestions and recommendations that will help you make your webxr app as performant as possible. rendering tips ... talk about general stuff like limiting how many different
loops there are during rendering, avoiding unnecessary drawing, etc. can probably also include stuff from https://github.com/immersive-web/webxr/blob/master/explainer.md#changing-the-field-of-view-for-inline-sessions managing rendering quality ... this section will come in part from https://github.com/immersive-web/webxr/blob/master/explainer.md#controlling-rendering-quality managing frame rate ...
...he object if needed mat4.rotate( } } this renders a scene. but it's inefficient, because it allocates as local variables a number of things, including at least two matrices, an array of vertices, and more. ...
...this has multiple benefits: the memory allocated for each value or structure will not need to be reallocated every frame. this reduces the potential for triggering garbage collection, and optimizes memory use. ...
Migrating from webkitAudioContext - Web APIs
e: var src = context.createbuffersource(); src.buffer = somebuffer; src.buffer.gain = 0.5; src.connect(context.destination); src.noteon(0); // new standard audiocontext code: var src = context.createbuffersource(); src.buffer = somebuffer; var gain = context.creategain(); src.connect(gain); gain.gain.value = 0.5; gain.connect(context.destination); src.start(0); removal of audiobuffersourcenode.
looping the
looping attribute of audiobuffersourcenode has been removed. this attribute was an alias of the
loop attribute, so you can just use the
loop attribute instead. instead of having code like this: var source = context.createbuffersource(); source.
looping = true; you can change it to respect the last version of the specification: var source = context.createbuffersource(); source.
loop = t...
... changes to determining playback state the playbackstate attribute of audiobuffersourcenode and oscillatornode has been removed. ...
... changes to determining playback state the playbackstate attribute of audiobuffersourcenode and oscillatornode has been removed. ...
HTTP Index - HTTP
ver. it is used by the server to indicate which headers it used when selecting a representation of a resource in a content negotiation algorithm. 194 via http, reference, header the via general header is added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. it is used for tracking message forwards, avoiding request
loops, and identifying the protocol capabilities of senders along the request/response chain. 195 www-authenticate http, http header, reference, response header, header the http www-authenticate response header defines the authentication method that should be used to gain access to a resource. 196 want-digest http, http header the want-digest http header is pr...
...ta to the server. the type of the body of the request is indicated by the content-type header. 214 put http, http method, reference, request method the http put request method creates a new resource or replaces a representation of the target resource with the request payload. 215 trace http, reference, trace method the http trace method performs a message
loop-back test along the path to the target resource, providing a useful debugging mechanism. 216 http resources and specifications guide, http http was first specified in the early 1990s. designed with extensibility in mind, it has seen numerous additions over the years; this lead to its specification being scattered through numerous specification documents (in the midst of exper...
... client to retrieve the best variant of a given resource, where the server supports multiple variants. 268 507 insufficient storage http, server error, status code the hypertext transfer protocol (http) 507 insufficient storage response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol (see rfc 4918). 269 508
loop detected 508, http, server error, status code the hypertext transfer protocol (http) 508
loop detected response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol. 270 511 network authentication required http, http status code, reference, server error, status code the http 511 network authentication required res...
Iterators and generators - JavaScript
« previousnext » processing each of the items in a collection is a very common operation. javascript provides a number of ways of iterating over a collection, from simple for
loops to map() and filter(). iterators and generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of
loops. for details, see also: iteration_protocols for...of function* and generator yield and yield* iterators in javascript an iterator is an object which defines a sequence and potentially a return value upon its termination. specifically, an iterator is any object which implements the iterator protocol by having a next() method that returns an object with two properties: value the next value in the iteratio...
...vior of this code is identical, but the implementation is much easier to write and read. function* makerangeiterator(start = 0, end = 100, step = 1) { let iterationcount = 0; for (let i = start; i < end; i += step) { iterationcount++; yield i; } return iterationcount; } iterables an object is iterable if it defines its iteration behavior, such as what values are
looped over in a for...of construct. some built-in types, such as array or map, have a default iteration behavior, while other types (such as object) do not. in order to be iterable, an object must implement the @@iterator method. this simply means that the object (or one of the objects up its prototype chain) must have a property with a symbol.iterator key. it may be possible to iterate over an ite...
...d 2; yield 3; } } for (let value of myiterable) { console.log(value); } // 1 // 2 // 3 or [...myiterable]; // [1, 2, 3] built-in iterables string, array, typedarray, map and set are all built-in iterables, because their prototype objects all have a symbol.iterator method. syntaxes expecting iterables some statements and expressions expect iterables. for example: the for-of
loops, yield*. for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); a; // "a" advanced generators generators compute their yielded values on demand, which allows them to efficiently represent sequences th...
JavaScript error reference - JavaScript
literals and octal escape seq. are deprecatedsyntaxerror: "use strict" not allowed in function with non-simple parameterssyntaxerror: "x" is a reserved identifiersyntaxerror: json.parse: bad parsingsyntaxerror: malformed formal parametersyntaxerror: unexpected tokensyntaxerror: using //@ to indicate sourceurl pragmas is deprecated. ...
...or: "x" is a reserved identifiersyntaxerror: json.parse: bad parsingsyntaxerror: malformed formal parametersyntaxerror: unexpected tokensyntaxerror: using //@ to indicate sourceurl pragmas is deprecated. ...
...peerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in
loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
Array.prototype.forEach() - JavaScript
skipped. (see this example, below.) foreach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. ...
...and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach()
loop other than by throwing an exception. if you need such behavior, the foreach() method is the wrong tool. early termination may be accomplished with: a simple for
loop a for...of / for...in
loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. kindly make sure yo...
...xamples 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. ...
TypedArray.prototype[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
... the initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
...initial value of the @@iterator property is the same function object as the initial value of the values property. syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default. ...
TypedArray.prototype.entries() - JavaScript
object that contains the key/value pairs for each index in the array. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.entries() return value a new array iterator object. ...
...red in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.entries() return value a new array iterator object. ...
...e to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.entries() return value a new array iterator object. ...
TypedArray.prototype.keys() - JavaScript
rray iterator object that contains the keys for each index in the array. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a new array iterator object. ...
...is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a new array iterator object. ...
...'d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.keys() return value a new array iterator object. ...
TypedArray.prototype.values() - JavaScript
iterator object that contains the values for each index in the array. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.values() return value a new array iterator object. ...
...tored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.values() return value a new array iterator object. ...
...ike to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.values() return value a new array iterator object. ...
Statements and declarations - JavaScript
e statements may occur on a single line if each statement is separated by a semicolon. this isn't a keyword, but a group of keywords. statements and declarations by category for an alphabetical listing see the sidebar on the left. control flow block a block statement is used to group zero or more statements. the block is delimited by a pair of curly brackets. break terminates the current
loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue terminates execution of the statements in the current iteration of the current or labeled
loop, and continues execution of the
loop with the next iteration. empty an empty statement is used to provide no statement, although the javascript syntax would expect one. if...else ...
...const declares a read-only named constant. functions and classes function declares a function with the specified parameters. function* generator functions enable writing iterators more easily. async function declares an async function with the specified parameters. return specifies the value to be returned by a function. class declares a class. iterations do...while creates a
loop that executes a specified statement until the test condition evaluates to false. the condition is evaluated after executing the statement, resulting in the specified statement executing at least once. for creates a
loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the
loop. for each...in iterates a spec...
...ects (including arrays, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property. 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. while creates a
loop that executes a specified statement as long as the test condition evaluates to true. the condition is evaluated before executing the statement. others debugger invokes any available debugging functionality. if no debugging functionality is available, this statement has no effect. export used to export functions to make them available for imports in external modules, and other scripts. im...
Optimizing startup performance - Web Performance
all your startup code in a single event handler on the app's main thread. instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event
loop continues to cycle while it starts up. this will prevent the app, browser, and/or device from appearing to have locked up. why is it important to be asynchronous? other than the reasons suggested above, consider the impact of a non-responsive page or user interface. the user is unable to cancel if they launched your app by mistake. if the app is being run in a browser, it's possible the user may...
...o start up nicely. on the other hand, however, it can get tricky when you're porting an existing app to the web. a desktop application doesn't need to be written in an asynchronous fashion because usually the operating system handles that for you, or the app is the only thing that matters which is currently running, depending on the operating environment. the source application might have a main
loop that can easily be made to operate asynchronously (by running each main
loop iteration separately); startup is often just a continuous, monolithic procedure that might periodically update a progress meter. while you can use web workers to run even very large, long-duration chunks of javascript code asynchronously, there's a huge caveat that: workers don't have access to webgl or audio, and they ...
...lticore processors. porting issues once the initial loading is done and the app's main code starts to run, it's possible your app may necessarily be single-threaded,especially if it's a port. the most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main
loop, so that the main thread gets to handle input and the like. emscripten provides an api to help with this refactoring; for example, you can use emscripten_push_main_
loop_blocker() to establish a function to be executed before the main thread is allowed to continue. by establishing a queue of functions to be called in sequence, you can more easily manage running bits of code without blocking the m...
lang/functional - Archive of obsolete content
rget.number += x; } console.log(mynumber.number); // 0 mynumber.add(10); // 10 mynumber.times(2); // 20 mynumber.add(3); // 23 parameters lambda : function the function to be wrapped and returned. returns function : the wrapped lambda. defer(fn) takes a function and returns a wrapped version of the function. calling the wrapped version will call the original function during the next event
loop. this is similar to calling settimeout with no wait (i.e. settimeout(function () { ... }, 0)), except that the wrapped function may be reused and does not need to be repeated each time. this also enables you to use these functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("cli...
...hese functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // this will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myevent` // function, making it non-blocking and executing on the // next event
loop parameters fn : function the function to be deferred. returns function : the new, deferred function. remit() an alias for defer. invoke(callee, params, self) invokes callee, passing params as an argument and self as this. returns the value that is returned by callee. let { invoke } = require("sdk/lang/functional"); invoke(sum, [1,2,3,4,5], null); // 15 function sum () { return array...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
, this will finally call processldapvalues, "3)" just above. // go through the ldap replicas list for(i = 0; i < ldap_servers.length; i ++) { // search for attribute mail & cn through ldap servers where uid = $user|$username getldapattributes(ldap_servers[i], "ou=people,dc=int-evry,dc=fr", "uid=" + env_user, "uid,cn,mail"); // if we catch a running ldap server, exit the
loop, if(ldap_values) { running_ldap_server = ldap_servers[i]; // if $mozilla_debug=1 display in a popup the running server if (env_mozdebug) { displayerror("getldapattributes: debug 2 running_ldap_server: " + running_ldap_server); } break; } } unique script for windows and linux an if... else test permits us to check whether we use a linux or win...
..., this will finally call processldapvalues, "3)" just above. ...
Nanojit - Archive of obsolete content
ento->getanchor((void *)0xdeadbeef); f->lirbuf = buf; f->root = f; // create a lir writer lirbufwriter out(buf); // write a few lir instructions to the buffer: add the first parameter // to the constant 2. out.ins0(lir_start); lins *two = out.insimm(2); lins *firstparam = out.insparam(0, 0); lins *result = out.ins2(lir_add, firstparam, two); out.ins1(lir_ret, result); // emit a lir_
loop instruction. it won't be reached, but there's // an assertion in nanojit that trips if a fragment doesn't end with // a guard (a bug in nanojit). lins *rec_ins = out.insskip(sizeof(guardrecord) + sizeof(sideexit)); guardrecord *guard = (guardrecord *) rec_ins->payload(); memset(guard, 0, sizeof(*guard)); sideexit *exit = (sideexit *)(guard + 1); guard->exit = exit; guard->exit->target = ...
..., but there's // an assertion in nanojit that trips if a fragment doesn't end with // a guard (a bug in nanojit). lins *rec_ins = out.insskip(sizeof(guardrecord) + sizeof(sideexit)); guardrecord *guard = (guardrecord *) rec_ins->payload(); memset(guard, 0, sizeof(*guard)); sideexit *exit = (sideexit *)(guard + 1); guard->exit = exit; guard->exit->target = f; f->lastins = out.insguard(lir_
loop, out.insimm(1), rec_ins); // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->error() != none) { fprintf(stderr, "error compiling fragment\n"); return 1; } printf("compilation successful.\n"); // call the compiled function. typedef js_fastcall int32_t (*addtwofn)(int32_t); addtwofn fn = reinterpret_cast<addtwofn>(f->code()); printf("2 + 5 ...
for each...in - Archive of obsolete content
the for each...in statement is deprecated as the part of ecma-357 (e4x) standard. e4x support has been removed. consider using for...of instead. firefox now warns about the usage of for each...in and it no longer works starting with firefox 57. please see warning: javascript 1.6's for-each-in
loops are deprecated for migration help. the for each...in statement iterates a specified variable over all values of object's properties. for each distinct property, a specified statement is executed. syntax for each (variable in object) { statement } variable variable to iterate over property values, optionally declared with the var keyword. this variable is local to the function, not to the
loop. object object for which the properties are iterated. statement a statement to exe...
... specified statement is executed. syntax for each (variable in object) { statement } variable variable to iterate over property values, optionally declared with the var keyword. this variable is local to the function, not to the
loop. object object for which the properties are iterated. statement a statement to execute for each property. to execute multiple statements within the
loop, use a block statement ({ ... }) to group those statements. description some built-in properties are not iterated over. these include all built-in methods of objects, e.g. string's indexof method. however, all user-defined properties are iterated over. examples using for each...in warning: never use a
loop like this on arrays. only use it on objects. see for...in for more details. the foll...
Old Proxy API - Archive of obsolete content
return true; } receiver is either the proxy or an object that inherits from the proxy. for(prop in proxy){...} enumerate: function() -> string array function() { return this.getpropertynames().filter( function (name) { return this.getpropertydescriptor(name).enumerable } ); } from the proxy user point of view, properties appear in the for..in
loop in the same order as they are in the returned array. object.keys(proxy) keys: function() -> string array function() { return this.getownpropertynames().filter( function (name) { return this.getownpropertydescriptor(name).enumerable } ); } invariants even though proxies provide a lot of power to users, some operations are not trapped in order...
...o implement at least all fundamental traps. unwanted recursion. be careful of how you use the receiver argument in 'get' and 'set' traps. var p = proxy.create({get: function(receiver, name) { print(receiver); // looks for receiver's tostring method. receiver turns out to be the proxy, so calling print results in calling the get trap. ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
r java.lang.class.forname( "com.mysql.jdbc.driver" ); // create connection to the database var conn = drivermanager.getconnection( "jdbc:mysql://localhost/rhino", "urhino", "prhino" ); // create a statement handle var stmt = conn.createstatement(); // get a resultset var rs = stmt.executequery( "select * from employee" ); // get the metadata from the resultset var meta = rs.getmetadata(); //
loop over the records, dump out column names and values while( rs.next() ) { for( var i = 1; i <= meta.getcolumncount(); i++ ) { print( meta.getcolumnname( i ) + ": " + rs.getobject( i ) + "\n" ); } print( "----------\n" ); } // cleanup rs.close(); stmt.close(); conn.close(); this code starts off by using a rhino function named importpackage which is just like using the import ...
...: ' + comment.@id + '<br/>'); document.write('name: ' + comment.@name + '<br/>'); document.write('message: ' + comment.@message + '<br/>'); document.write('<hr/>'); } </script> the code in listing 11 is very simple. first a call to get the xml feed is made using the get method from the jaxer.web namespace, using the option that requests the response as a new e4x object. the comment nodes are
looped over with data output using the simplified e4x syntax. out of all the features we looked at, this one has to be my favorite. to be able to use jaxer to essentially create an xml based restful service in javascript is useful and shifts a great deal of power to the javascript developer. conclusion javascript can be successfully used for full application development on ...
Building up a basic demo with the PlayCanvas engine - Game development
code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update
loop. add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the pc global object contains all the playcanvas functions available in the engine. next, we'll set the canvas to fill the window, and automatically change its resolution to be the same as the canvas size. again, add the following lines at the bottom of your script. app.s...
...me something is usually happening — we can see animations and such — so let's try to breathe a little life into those shapes by animating them. animation we already used translate or rotate to adjust the position of the shapes; we could also change their positions directly with setposition, or scale them. to show actual animation, we need to make changes to these values inside the rendering
loop, so they are updated on every frame. there's a special update event that we can use for that — add the following code just below the previous additions: var timer = 0; app.on("update", function (deltatime) { timer += deltatime; // code executed on every frame }); the callback takes the deltatime as the parameter, so we have the relative time that has passed since the previous invocat...
Building up a basic demo with Three.js - Game development
little help from requestanimationframe(), which causes the scene to be re-rendered constantly on every frame: function render() { requestanimationframe(render); renderer.render(scene, camera); } render(); on every new frame the render function is invoked, and the renderer renders the scene and the camera. right after the function declaration, we're invoking it for the first time to start the
loop, after which it will be used indefinitely. again, add this new code below your previous additions. try saving the file and opening it in your browser. you should now see a gray window. congratulations! geometry now our scene is properly rendering, we can start adding 3d shapes. to speed up development, three.js provides a bunch of predefined primitives, which you can use to create shapes insta...
.... this looks a little boring though. in a game, something is usually happening. we might see animations and such. so let's try breathing a little life into these shapes, by animating them! animation we already used rotation, to adjust the position of the cube. we can also scale the shapes, or change their positions. to show animation, we need to make changes to these values inside the render
loop, so they update on each frame. rotation rotating is straighforward. you add a value to a given direction of rotation on each frame. add this line of code, right after the requestanimationframe() invocation inside the render function: cube.rotation.y += 0.01; this rotates the cube on every frame, by a tiny bit, so the animation looks smooth. scaling we can also scale an object. applying a c...
Unconventional controls - Game development
and is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. ...
...r the state of our hand's grab status. ...
Collision detection - Game development
t the easiest way possible. we will check if the center of the ball is colliding with any of the given bricks. this won't give a perfect result every time, and there are much more sophisticated ways to do collision detection, but this will work fine for teaching you the basic concepts. ...
... but this will work fine for teaching you the basic concepts. a collision detection function to kick this all off we want to create a collision detection function that will
loop through all the bricks and compare every single brick's position with the ball's coordinates as each frame is drawn. for better readability of the code we will define the b variable for storing the brick object in every
loop of the collision detection: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; // calculations } } } if the center of the ball is inside the coordinates of one of our bricks, we'll change the direction of the ball. for the center of the ball to be inside the brick, all...
Finishing up - Game development
compare your code that's all — the final version of the game is ready and set to go ! exercise: change th...
... compare your code that's all — the final version of the game is ready and set to go ! exercise: change the number of lives and the angle the ball bounces off the paddle. ...
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
in computer science, a boolean is a logical data type that can have only the values true or false. for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for
loops). below is some javascript pseudocode (it's not truly executable code) demonstrating this concept. ...
...such as in for
loops). below is some javascript pseudocode (it's not truly executable code) demonstrating this concept. /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for
loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { console.log("i print only when the boolean conditional is true"); } the boolean value is named after english mathematician george boole, who pioneered the field of mathematical logic. learn more general knowledge boolean on wikipedia techni...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
for example, imagine a script used to validate user data from a webpage form. the script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. ...
... leaves a required field empty, the script prompts them to fill it in. to do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is complete or not: if (field==empty) { promptuser(); } else { submitform(); } a typical script in javascript or php (and the like) includes many control structures, including conditionals,
loops and functions. parts of a script may also be set to execute when events occur. for example, the above excerpt might be inside a function that runs when the user clicks the submit button for the form. the function could also include a
loop, which iterates through all of the fields in the form, checking each one in turn. looking back at the code in the if and else sections, the lines promptuser a...
Video and audio content - Learn web development
sary use of resources. refer to our guide to media types and formats for help selecting the best containers and codecs for your needs, as well as to look up the right mime types to specify for each. other <video> features there are a number of other features you can include when displaying an html video. take a look at our next example: <video controls width="400" height="400" autoplay
loop muted preload="auto" poster="poster.png"> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html video. here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> the resulting ui looks something like this: the new features are: width and height you can control the video size eithe...
...aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default. autoplay makes the audio or video start playing right away, while the rest of the page is loading. you are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
loop makes the video (or audio) start playing again whenever it finishes. this can also be annoying, so only use if really necessary. muted causes the media to play with the sound turned off by default. poster the url of an image which will be displayed before the video is played. it is intended to be used for a splash screen or advertising screen. preload used for buffering large files; it c...
Client-side storage - Learn web development
ample, and the code is well-commented. for this simple example, we've stored the names of the videos to fetch in an array of objects: const videos = [ { 'name' : 'crystal' }, { 'name' : 'elf' }, { 'name' : 'frog' }, { 'name' : 'monster' }, { 'name' : 'pig' }, { 'name' : 'rabbit' } ]; to start with, once the database is successfully opened we run an init() function. this
loops through the different video names, trying to load a record identified by each name from the videos database. if each video is found in the database (easily checked by seeing whether request.result evaluates to true — if the record is not present, it will be undefined), its video files (stored as blobs) and the video name are passed straight to the displayvideo() function to place them in th...
...ked by seeing whether request.result evaluates to true — if the record is not present, it will be undefined), its video files (stored as blobs) and the video name are passed straight to the displayvideo() function to place them in the ui. if not, the video name is passed to the fetchvideofromnetwork() function to ... you guessed it — fetch the video from the network. ...
Basic math in JavaScript — numbers and operators - Learn web development
ract one to or from a numeric variable value. this can be conveniently done using the increment (++) and decrement (--) operators. we used ++ in our "guess the number" game back in our first splash into javascript article, when we added 1 to our guesscount variable to keep track of how many guesses the user has left after each turn. guesscount++; note: these operators are most commonly used in
loops, which you'll learn about later on in the course. for example, say you wanted to
loop through a list of prices, and add sales tax to each one. you'd use a
loop to go through each value in turn and do the necessary calculation for adding the sales tax in each case. the incrementor is used to move to the next value when needed. we've actually provided a simple example showing how this is done — ...
... let's try playing with these in your console. for a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. ...
Solve common problems in your JavaScript code - Learn web development
with objects, however, you need to take care to use the correct syntax. the object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. ...
...s of code, depending on a variable's value or other condition? how do you use if ...else statements? how do you nest one decision block inside another? how do you use and, or, and not operators in javascript? how do you conveniently handle a large number of choices for one condition? how do you use a ternary operator to make a quick choice between two options based on a true or false test?
looping/iteration how do you run the same bit of code over and over again? how do you exit a
loop before the end if a certain condition is met? how do you skip to the next iteration of a
loop if a certain condition is met? how do you use while and do ... while
loops? how do you iterate over the elements in an array? how do you iterate over the elements in a multidimensional array? how do you ...
Adding features to our bouncing balls demo - Learn web development
nt, you no longer want to make the objects change color when a collision is detected — instead, you want to set any balls that collide with the evil circle to not exist any more (again, how do you think you'd do that?). bringing the evil circle into the program now we've defined the evil circle, we need to actually make it appear in our scene. ...
... bringing the evil circle into the program now we've defined the evil circle, we need to actually make it appear in our scene. to do this, you need to make some changes to the
loop() function. first of all, create a new evil circle object instance (specifying the necessary parameters), then call its setcontrols() method. you only need to do these two things once, not on every iteration of the
loop. at the point where you
loop through every ball and call the draw(), update(), and collisiondetect() functions for each one, make it so that these functions are only called if the current ball exists. call the evil ball instance's draw(), checkbounds(), and collisiondetect() methods on every iteration of the
loop. implementing the score counter to implement the score counter, follow the foll...
Inheritance in JavaScript - Learn web development
, loading the page in a browser, and entering teacher.prototype.constructor into the console to verify. this can become a problem, so we need to set this right. you can do so by going back to your source code and adding the following line at the bottom: object.defineproperty(teacher.prototype, 'constructor', { value: teacher, enumerable: false, // so that it does not appear in 'for in'
loop writable: true }); now if you save and refresh, entering teacher.prototype.constructor should return teacher(), as desired, plus we are now inheriting from person()! giving teacher() a new greeting() function to finish off our code, we need to define a new greeting() function on the teacher() constructor. the easiest way to do this is to define it on teacher()'s prototype — add the f...
... of where you define your methods and properties. it is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. too much inheritance can lead to endless confusion, and endless pain when you try to debug such code. ultimately, objects are just another form of code reuse, like functions or
loops, with their own specific roles and advantages. if you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. objects are also very useful when you want to pass a collection of data from one place to another. both of these things can be achieved without use of constructors or inheritance. if you only...
Working with JSON - Learn web development
cle.appendchild(myh2); myarticle.appendchild(mypara1); myarticle.appendchild(mypara2); myarticle.appendchild(mypara3); myarticle.appendchild(mylist); section.appendchild(myarticle); } } to start with, we store the members property of the javascript object in a new variable. this array contains multiple objects that contain the information for each hero. next, we use a for
loop to
loop through each object in the array. for each one, we: create several new elements: an <article>, an <h2>, three <p>s, and a <ul>. set the <h2> to contain the current hero's name. fill the three paragraphs with their secretidentity, age, and a line saying "superpowers:" to introduce the information in the list. store the powers property in another new constant called superpowers — th...
...w elements: an <article>, an <h2>, three <p>s, and a <ul>. set the <h2> to contain the current hero's name. fill the three paragraphs with their secretidentity, age, and a line saying "superpowers:" to introduce the information in the list. store the powers property in another new constant called superpowers — this contains an array that lists the current hero's superpowers. use another for
loop to
loop through the current hero's superpowers — for each one we create an <li> element, put the superpower inside it, then put the listitem inside the <ul> element (mylist) using appendchild(). the very last thing we do is to append the <h2>, <p>s, and <ul> inside the <article> (myarticle), then append the <article> inside the <section>. the order in which things are appended is important, as...
Multimedia: video - Learn web development
sed video still looks good. there are some compression algorithms that can make video look (bad) like an animated gif. while a 128 kb video may seem like it could provide a better user experience than a 10 mb download, a grainy gif-like video may reflect poorly on the brand or project. see caniuse.com for current browser support of video and other media types. video autoplay to ensure that a
looping background video autoplays, you must add several attributes to the video tag: autoplay, muted, and playsinline. <video autoplay=""
loop="" muted="true" playsinline="" src="backgroundvideo.mp4"> while the
loop and autoplay make sense for a
looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers. playsinline is required for mobile safari, allowing videos...
..." src="backgroundvideo.mp4"> while the
loop and autoplay make sense for a
looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers. playsinline is required for mobile safari, allowing videos to play without forcing fullscreen mode. remove audio from muted hero videos for hero-video or other video without audio, removing audio is smart. <video autoplay=""
loop="" muted="true" playsinline="" id="hero-video"> <source src="banner_video.webm" type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> this hero-video code (above) is common to conference websites and corporate home pages. it includes a video that is auto-playing,
looping, and muted. there are no controls, so there is no way to hear audio. ...
Getting started with Svelte - Learn web development
native, which lets you build native mobile applications. how does svelte work? being a compiler, svelte can extend html, css, and javascript, generating optimal javascript code without any runtime overhead. to achieve this, svelte extends vanilla web technologies in the following ways: it extends html by allowing javascript expressions in markup and providing directives to use conditions and
loops, in a fashion similar to handlebars. it extends css by adding a scoping mechanism, allowing each component to define their own styles without the risk of clashing with other component's styles. it extends javascript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management. the compiler only intervenes in very specific situations and...
... if you just want to download the files without cloning the git repo, you can use the degit tool like this — npx degit opensas/mdn-svelte-tutorial. you can also download a specific folder with npx degit opensas/mdn-svelte-tutorial/01-getting-started. degit won't create a local git repo, it will just download the files of the specified folder. using the svelte repl a repl (read–eval–print
loop) is an interactive environment that allows you to enter commands and immediately see the results — many programming languages provide a repl. svelte's repl is much more than that. it's an online tool that allows you to create complete apps, save them online, and share with others. it's the easiest way to start playing with svelte from any machine, without having to install anything. it is als...
Handling common JavaScript problems - Learn web development
it applies to, and therefore if its value is what you intended. you can read what is "this"? for a light introduction; you should also study examples like this one, which shows a typical pattern of saving a this scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct this scope. incorrectly using functions inside
loops — for example, in bad-for-
loop.html (see source code), we
loop through 10 iterations, each time creating a paragraph and adding an onclick event handler to it. when clicked, each one should alert a message containing its number (the value of i at the time it was created), however each one reports i as 11, because for
loops do all their iterating before nested functions are invoked. if you want...
... making sure asynchronous operations have returned before trying to use the values they return. ...
Gecko Logging
ted a lot, useful for debugging program flow and will probably impact performance. ...
...it can also be adjusted by setting prefs. ...
Performance best practices for Firefox front-end engineers
owutils for a browser window, records the number of styleflushes, then synchronously calls the function that you want to test, and immediately after checks the styleflushes attribute again. if the value went up, your code caused synchronous style flushes to occur. note that your test and function must be called synchronously in order for this test to be accurate. if you ever go back to the event
loop (by yielding, waiting for an event, etc), style flushes unrelated to your code are likely to run, and your test will give you a false positive. detecting and avoiding synchronous reflow this is also sometimes called “sync layout”, "sync layout flushes" or “sync layout calculations” sync reflow is a term bandied about a lot, and has negative connotations. it's not unusual for an engin...
...hat information guide your timing when you ask questions in the gfx room . adding nodes using documentfragments sometimes you need to add several dom nodes as part of an existing dom tree. for example, when using xul <xul:menupopup>s, you often have script which dynamically inserts <xul:menuitem>s. inserting items into the dom has a cost. if you're adding a number of children to a dom node in a
loop, it's often more efficient to batch them into a single insertion by creating a documentfragment, adding the new nodes to that, then inserting the documentfragment as a child of the desired node. a documentfragment is maintained in memory outside the dom itself, so changes don't cause reflow. the api is straightforward: create the documentfragment by calling document.createdocumentfragment(). ...
OS.File for the main thread
ason; } } ); example: copy a file by chunks the following snippet writes a (presumably large) buffer by chunks. 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. if (pos <= view.bytelength) { // note: should this be pos >= view.bytelength ? return promise.resolve(true); //
loop end. } let promise = file.write(view.subarray(pos, chunksize)); // write a subset of |data| return promi...
... // define a recursive asynchronous
loop. if (pos <= view.bytelength) { // note: should this be pos >= view.bytelength ? return promise.resolve(true); //
loop end. } let promise = file.write(view.subarray(pos, chunksize)); // write a subset of |data| return promise.then(function onsuccess(bytes) { return
loop(pos + bytes); // ... and
loop. }); }; let promise =
loop(0); // enter the
loop. promise = promise.then(function onsuccess() { // once
loop is complete, finalize. file.close(); }, function onerror(reason) { file.close(); throw reason; }); return promise...
Gecko Profiler FAQ
nt to do more focused profiling on, so that you can find its name and then construct a more useful thread filter string based on the found thread name. how can i run (micro-?) benchmarks on the memory allocator to see if changes in it (or entire allocator replacements) are slower/faster? what you *don’t* want to do is writing a micro-benchmark that call malloc/free in a
loop and the like and call it a day! a better idea would be picking up a real browser workload where through previous profiling we know that malloc overhead contributes a measurable percentage of overhead to the overall time and then study the change to that workload after replacing the allocator. you do want to think about various characteristics of an allocator which may have...
...or random/independent? (i'd guess they're independent). when profiling hundred(s) of threads at low intervals, does this distort the measurement or operation? (i.e. i want to profile all threads, not just main plus a couple of others) we haven’t done any measurements of how frequent sampling distorts measurement or operation. there is only one sampler thread. it runs a
loop that works like this: iterate over all threads. for each thread, suspend it, walk its stack, resume it. sleep until the next sample is due. then go to the previous step. i there an equivalent to itimer_prof vs itimer_real settings? (itimer_prof interrupts every n ms regardless of which thread used the time, real interrupts every nms of ...
AsyncTestUtils extended framework
lete that does not occur synchronously (that is, it is not done when the function call you made to initiate the operation returns control to you). this is likely to happen when i/o is involved or a potentially expensive process wants to break itself up into smaller chunks (like a search operation) so that the ui stays responsive. in the mozilla platform, the "top level" of a program is the event
loop. it is a never-ending
loop that dequeues pending events and runs them. this is how asynchronous callbacks get their chance to run again. when i/o results in newly read data it places an event in the queue. when a timer fires because the requested duration is up, it also places an event in the queue. in order to give these events a chance to run we either need to make sure we yield control to the...
...nding
loop that dequeues pending events and runs them. this is how asynchronous callbacks get their chance to run again. when i/o results in newly read data it places an event in the queue. when a timer fires because the requested duration is up, it also places an event in the queue. in order to give these events a chance to run we either need to make sure we yield control to the top-level event
loop or spin our own nested event
loop. asynctestutils is currently implemented by the first method (yielding control to the top-level event
loop). mozmill is an example of a testing framework that uses a nested event
loop. in the future we will probably move the asynctestutils framework to a nested event
loop in a backwards-compatible fashion. how does this affect my tests? thanks to javascript enh...
PRSockOption
e pair. syntax #include <prio.h> typedef enum prsockoption { pr_sockopt_nonblocking, pr_sockopt_linger, pr_sockopt_reuseaddr, pr_sockopt_keepalive, pr_sockopt_recvbuffersize, pr_sockopt_sendbuffersize, pr_sockopt_iptimetolive, pr_sockopt_iptypeofservice, pr_sockopt_addmember, pr_sockopt_dropmember, pr_sockopt_mcastinterface, pr_sockopt_mcasttimetolive, pr_sockopt_mcast
loopback, pr_sockopt_nodelay, pr_sockopt_maxsegment, pr_sockopt_last } prsockoption; enumerators the enumeration has the following enumerators: pr_sockopt_nonblocking nonblocking i/o. pr_sockopt_linger time to linger on close if data is present in the socket send buffer. pr_sockopt_reuseaddr allow local address reuse. pr_sockopt_keepalive periodically test whether connection is stil...
...fer size. pr_sockopt_sendbuffersize send buffer size. pr_sockopt_iptimetolive ip time-to-live. pr_sockopt_iptypeofservice ip type-of-service and precedence. pr_sockopt_addmember join an ip multicast group. pr_sockopt_dropmember leave an ip multicast group. pr_sockopt_mcastinterface ip multicast interface address. pr_sockopt_mcasttimetolive ip multicast time-to-live. pr_sockopt_mcast
loopback ip multicast
loopback. pr_sockopt_nodelay disable nagle algorithm. don't delay send to coalesce packets. pr_sockopt_maxsegment maximum segment size. pr_sockopt_last always one greater than the maximum valid socket option numerator. description the prsockoption enumeration consists of all the socket options supported by nspr. the option field of prsocketoptiondata should be set to an...
PRSocketOptionData
type for structure used with pr_getsocketoption and pr_setsocketoption to specify options for file descriptors that represent sockets. syntax #include <prio.h> typedef struct prsocketoptiondata { prsockoption option; union { pruintn ip_ttl; pruintn mcast_ttl; pruintn tos; prbool non_blocking; prbool reuse_addr; prbool keep_alive; prbool mcast_
loopback; prbool no_delay; prsize max_segment; prsize recv_buffer_size; prsize send_buffer_size; prlinger linger; prmcastrequest add_member; prmcastrequest drop_member; prnetaddr mcast_if; } value; } prsocketoptiondata; fields the structure has the following fields: ip_ttl ip time-to-live. mcast_ttl ip multicast time-to-live. tos ip type-of-service and preced...
... prmcastrequest drop_member; prnetaddr mcast_if; } value; } prsocketoptiondata; fields the structure has the following fields: ip_ttl ip time-to-live. mcast_ttl ip multicast time-to-live. tos ip type-of-service and precedence. non_blocking nonblocking (network) i/o. reuse_addr allow local address reuse. keep_alive periodically test whether connection is still alive. mcast_
loopback ip multicast
loopback. no_delay disable nagle algorithm. don't delay send to coalesce packets. max_segment tcp maximum segment size. recv_buffer_size receive buffer size. send_buffer_size send buffer size. linger time to linger on close if data are present in socket send buffer. add_member join an ip multicast group. drop_member leave an ip multicast group. mcast_if ip multic...
Encrypt Decrypt MAC Keys As Session Objects
char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file *
loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secst...
...to it. * generate a symmetric aes key as a token object. * generate a second key to use for macing, also a token object. * get their cka_ids * generate a random value to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
Encrypt and decrypt MAC using token
char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file *
loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secst...
...to it. * generate a symmetric aes key as a token object. * generate a second key to use for macing, also a token object. * get their cka_ids * generate a random value to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
Encrypt Decrypt_MAC_Using Token
*outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it: * open input file, read in header, get iv and cka_ids of two keys from it. * find those keys in the db token. * open output file. *
loop until eof(input): * read a buffer of ciphertext from input file. * save last block of ciphertext. * decrypt ciphertext buffer using cbc and iv. * compute and check mac, then remove mac from plaintext. * replace iv with saved last block of ciphertext. * write the plain text to output file. * close files. * report success. */ ...
...to it. * generate a symmetric aes key as a token object. * generate a second key to use for macing, also a token object. * get their cka_ids * generate a random value to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
NSS Sample Code Sample_3_Basic Encryption and MACing
nst char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file *
loop until eof(input): * read a buffer of ciphertext from input file * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secstat...
... to it. * generate a symmetric aes key as a token object. * generate a second key to use for macing, also a token object. * get their cka_ids * generate a random value to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
EncDecMAC using token object - sample 3
return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file *
loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secstatus rv; secitem ivitem; secitem enckeyitem; secitem mackeyitem; secitem c...
... for read/write and we have authenticated to it. * generate a symmetric aes key as a token object. * generate a second key to use for macing, also a token object. * get their cka_ids * generate a random value to use as iv for aes cbc * open an input file and an output file, * write a header to the output that identifies the two keys by * their cka_ids, may include original file name and length. ...
Invariants
) all jsobjects and heap-allocated jsstrings must be 8-byte-aligned. (the jsval encoding depends on this.) the jsstackframe::down chain never forms a cycle. (it's a stack. but note that a stack frame is not necessarily newer than the next stack frame down, thanks to generators!) an object's scope chain (found by chasing jsobject::fslots[jsslot_parent]) never forms a cycle. (we can probably
loop forever if that happens. js_setparent can violate this, if the application is really that dumb, but generally every object is newer than its __parent__.) the tracejit must not trace into a function whose scope chain ends in a different global object. (if it is a script function, global names accessed in that function would refer to a different global object. even if the function is native, ther...
... the function is native, there is serious trouble: js_newobject with null parent argument calculates the parent from cx->fp->scopechain, which can be stale if we're on trace.) the chain of properties starting at any jsshape and chasing jsshape::parent never forms a cycle and does not contain any duplicate jsscopeproperty::slot values other than -1. (a cycle would be very silly and could cause inf
loops. the same slot being allocated to more than one property would be a problem for obvious reasons.) all jsshapes in dictionary-mode objects have the in_dictionary flag set. all jsshapes in property trees have it cleared. if an object is inextensible, its dslots will never again change. (we don't bother locking when accessing slots of a sealed object. the locking is going away regardless.) compa...
JS_Enumerate
on this jscontext. obj js::handleobject the object whose properties are to be enumerated. description js_enumerate gets the ids of all own properties of the specified object, obj, that have the jsprop_enumerate attribute. (the term own property refers to a property that is not inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in
loop, which converts all property ids to strings and also enumerates inherited properties. this calls obj's jsclass.enumerate hook. on success, js_enumerate returns a pointer to the first element of an array of property ids. the application must free this array using js_destroyidarray. on error or exception, js_enumerate returns null. the property ids in the returned jsidarray are subject to garbage...
...s a pointer to the first element of an array of property ids. the application must free this array using js_destroyidarray. on error or exception, js_enumerate returns null. the property ids in the returned jsidarray are subject to garbage collection. as long as obj is reachable, its current property ids are reachable. but, for example, if an application calls back into javascript while it is
looping over the property ids in the jsidarray, the script could delete properties from obj. the property ids would then become unreachable and could be collected. therefore a program that
loops over the property ids must either root them all, ensure that the properties are not deleted (in a multithreaded program this requires even greater care), or ensure that garbage collection does not occur. see...
XPCOM array guide
le arrays like nsiarray however, the enumeration mechanism is often preferred because it avoids the addref / release overhead that comes from accessing each object. the only functional drawback to in-place enumeration is that you cannot manipulate the array itself during the enumeration. for example, you should not delete elements of an array during the enumeration as this will often confuse the
loop which is enumerating the array. enumerators most arrays provide access to an object which is used to enumerate members of the array. these enumerators maintain state about the current position in the array. enumerators are used to access the elements in an ordered way, without relying on the underlying array type. these enumerators include: nsisimpleenumerator - an enumerator for com objects...
...the callback mechanism can be useful when integrating with existing callback-style code however. one particularly nice thing about the callback mechanism is that it is typesafe. for instance: pr_callback prbool getfirstvisible(nsielement* element, void* closure) { prbool isvisible; element->isvisible(&isvisible); // stop at first object if (isvisible) { ns_static_cast(c...
imgIContainer
that would be drawn if the image was to be drawn now. read only. obsolete since gecko 2.0 currentframeisopaque boolean whether the current frame is opaque; that is, needs the background painted behind it. read only. height print32 the height of the container rectangle. in the case of any error, zero is returned, and an exception will be thrown. read only.
loopcount long number of times to
loop the image. note: -1 means forever. obsolete since gecko 2.0 numframes unsigned long the total number of frames in this image. read only. obsolete since gecko 2.0 preferredalphachannelformat gfx_format read only. obsolete since gecko 1.9.2 type unsigned short the type of this image (one of the type_* valu...
...ecifying various "special" frames. frame_first: the first frame frame_current: the current frame. frame_max_value should be set to the value of the maximum constant above, as it is used for ensuring that a valid value was passed in. frame_current 1 frame_max_value 1 knormalanimmode 0 animation mode constants 0 = normal 1 = do not animate 2 =
loop once. kdontanimmode 1 k
looponceanimmode 2 kdisposeclearall -1 "disposal" method indicates how the image should be handled before the subsequent image is displayed. do not change these without looking at the implementations using them, struct gif_struct::disposal_method and gif_write() in particular. clear() the whole image, revealing. obs...
nsIAppShellService
rs acmdlineservice is stored and passed to appshell components as they are initialized. nativeappsupportorsplashscreen is an object that can be queryinterface'd to either an nsinativeappsupport or nsisplashscreen; this object will be used to implement hidesplashscreen. quit() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) exit the event
loop, shut down the app. void quit( in pruint32 aferocity ); parameters aferocity one of the e* constants. createwindowlessbrowser() this method creates a browser that does not have a window. if the browser is exited, this windowless browser will not prevent firefox from exiting. e10s notes: the browser is created in process. to get an out of process element you want to communicate with ...
... knows it can not quit until it is out of registered windows. note: when this method is successful, it fires the global notification "xul-window-registered" void registertoplevelwindow( in nsixulwindow awindow ); parameters awindow the window to register. run() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) runs an application event
loop: normally the main event pump which defines the lifetime of the application. void run(); parameters none. toplevelwindowismodal() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the appshell service needs to be informed of modal xul windows currently open. call this method as a window becomes modal or as it becomes nonmodal. void topleve...
nsIAppStartup
obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) required initialization routine. void initialize( in nsisupports nativeappsupportorsplashscreen ); parameters nativeappsupportorsplashscreen is an object that can be qi'd to either an nsinativeappsupport or nsisplashscreen; this object will be used to implement hidesplashscreen. quit() exit the event
loop, and shut down the application. void quit( in pruint32 amode ); parameters amode this parameter modifies how the application is shutdown, and it is constructed from the constants defined above. restartinsafemode() restart the application in safe mode. void quit( in pruint32 aquitmode ); parameters aquitmode this parameter modifies how the app is shutdown. run() runs an app...
... the application. void quit( in pruint32 amode ); parameters amode this parameter modifies how the application is shutdown, and it is constructed from the constants defined above. restartinsafemode() restart the application in safe mode. void quit( in pruint32 aquitmode ); parameters aquitmode this parameter modifies how the app is shutdown. run() runs an application event
loop: normally the main event pump which defines the lifetime of the application. if there are no windows open and no outstanding calls to enterlastwindowclosingsurvivalarea() this method will exit immediately. void run(); parameters none. return value returns ns_success_restart_app code. this return code indicates that the application should be restarted because quit was called with the erestar...
nsIServerSocket
a summary to this article. last changed in gecko 1.6 inherits from: nsisupports implemented by: @mozilla.org/network/server-socket;1. to create an instance, use: var serversocket = components.classes["@mozilla.org/network/server-socket;1"] .createinstance(components.interfaces.nsiserversocket); method overview void init(in long aport, in boolean a
loopbackonly, in long abacklog); void initwithaddress([const] in prnetaddrptr aaddr, in long abacklog);native code only! void close(); void asynclisten(in nsiserversocketlistener alistener); prnetaddr getaddress();native code only! attributes attribute type description port long returns the port of this server socket. read only.
...ed out to indicate a server socket bound to all network devices. therefore, this method cannot be used to determine the ip address of the local system. see nsidnsservice.myhostname() if this is what you need. prnetaddr getaddress(); parameters none. return value the network address to which the socket is bound. init() initializes a server socket. void init( in long aport, in boolean a
loopbackonly, in long abacklog ); parameters aport the port of the server socket. pass -1 to indicate no preference, and a port will be selected automatically. a
loopbackonly if true, the server socket will only respond to connections on the local
loopback interface. otherwise, it will accept connections from any interface. to specify a particular network interface, use initwithaddress(). ab...
WebIDL bindings
e every time the method or getter is called even if no gecko code ran between the calls. nothing the return value is a constant that never changes. this value cannot be used on non-readonly attributes, since having a non-readonly attribute whose value never changes doesn't make sense. values other than everything, when used in combination with [affects=nothing], can used by the jit to perform
loop-hoisting and common subexpression elimination on the return values of idl attributes and methods. [affects] used for a method or attribute getter to indicate what sorts of state can be affected when the function is called. attribute setters are, for now, assumed to affect everything. possible values are: everything this value can't actually be specified explicitly; this is the default value...
...getters with [affects=nothing] are allowed to throw exceptions, as long as they do so deterministically. in the case of methods, whether an exception is thrown is allowed to depend on the arguments, as long as calling the method with the same arguments will always either throw or not throw. the nothing value, when used with [dependson] values other than everything, can used by the jit to perform
loop-hoisting and common subexpression elimination on the return values of idl attributes and methods, as well as code motion past dom methods that might depend on system state but have no side effects. [pure] this is an alias for [affects=nothing, dependson=domstate]. attributes/methods flagged in this way promise that they will keep returning the same value as long as nothing that has [affects=eve...
Initialization and Destruction - Plugins
, top). the argn array contains the attribute names; the argv array contains the attribute values. the browser ignores any nonstandard attributes in an embed element, so the web page author can use the arg parameters to specify private attributes defined for a particular plug-in. ...
...e argv array contains the attribute values. the browser ignores any nonstandard attributes in an embed element, so the web page author can use the arg parameters to specify private attributes defined for a particular plug-in. for example, the following embed element has the standard attributes src, height, and width and the private attribute
loop: <embed src="movie.avi" height="100" width="100"
loop="true"> with the embed element in the example, the browser passes the values in argv to the plug-in instance: argc = 4 argn = { "src", "height", "width", "
loop" } argv = { "movie.avi", "100", "100", "true" } the saved parameter allows an instance of a plug-in to save its data and, when the instance is destroyed, pass the data to the next instance of the plug-in at the same url. the data is sa...
AudioProcessingEvent - Web APIs
ple the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to
loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = do...
...ata" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
BaseAudioContext.createDelay() - Web APIs
octx.createdelay(maxdelaytime); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by. must be less than 180 seconds, and defaults to 1 second if not specified. returns a delaynode. the default delaynode.delaytime is 0 seconds. example we have created a simple example that allows you to play three different samples on a constant
loop — see create-delay (you can also view the source code). if you just press the play buttons, the
loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(...
...elay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.
loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ... var delay1; rangesynth.oninput = function() { delay1 = rangesynth.va...
BaseAudioContext.createScriptProcessor() - Web APIs
ple the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to
loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = do...
...ata" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
BaseAudioContext.decodeAudioData() - Web APIs
he request to arraybuffer so that it returns an array buffer as its response that we then store in the audiodata variable . we then pass this buffer into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to
loop. the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively. when the stop() method is called on the source, the source is cleared out. note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselecto...
...tdata() { source = audioctx.createbuffersource(); var request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { source.buffer = buffer; source.connect(audioctx.destination); source.
loop = true; }, function(e){ console.log("error with decoding audio data" + e.err); }); } request.send(); } // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); } stop.onclick = function() { source.stop(0); play.removeattribute('disabled'); } // dump script to pre element pre.inne...
Transformations - Web APIs
te(x, y) moves the canvas and its origin on the grid. x indicates the horizontal distance to move, and y indicates how far to move the grid vertically. it's a good idea to save the canvas state before doing any transformations. in most cases, it is just easier to call the restore method than having to do a reverse translation to return to the original state. also if you're translating inside a
loop and don't save and restore the canvas state, you might end up missing part of your drawing, because it was drawn outside the canvas edge. a translate example this example demonstrates some of the benefits of translating the canvas origin. without the translate() method, all of the rectangles would be drawn at the same position (0,0). the translate() method also gives us the freedom to place the...
...ithout the translate() method, all of the rectangles would be drawn at the same position (0,0). the translate() method also gives us the freedom to place the rectangle anywhere on the canvas without having to manually adjust coordinates in the fillrect() function. this makes it a little easier to understand and use. in the draw() function, we call the fillrect() function nine times using two for
loops. in each
loop, the canvas is translated, the rectangle is drawn, and the canvas is returned back to its original state. note how the call to fillrect() uses the same coordinates each time, relying on translate() to adjust the drawing position. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ...
DelayNode.delayTime - Web APIs
argument of the audiocontext.createdelay() method that created it. syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example we have created a simple example that allows you to play three different samples on a constant
loop — see create-delay (you can also view the source code). if you just press the play buttons, the
loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(...
...elay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.
loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ... var delay1; rangesynth.oninput = function() { delay1 = rangesynth.va...
DelayNode - Web APIs
t.createdelay() factory method. properties inherits properties from its parent, audionode. delaynode.delaytime read only is an a-rate audioparam representing the amount of delay to apply, specified in seconds. methods no specific methods; inherits methods from its parent, audionode. example we have created a simple example that allows you to play three different samples on a constant
loop — see create-delay (you can also view the source code). if you just press the play buttons, the
loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(...
...elay will be introduced, so the
looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... var synthsource; playsynth.onclick = function() { synthsource = audioctx.createbuffersource(); synthsource.buffer = buffers[2]; synthsource.
loop = true; synthsource.start(); synthsource.connect(synthdelay); synthdelay.connect(destination); this.setattribute('disabled', 'disabled'); } stopsynth.onclick = function() { synthsource.disconnect(synthdelay); synthdelay.disconnect(destination); synthsource.stop(); playsynth.removeattribute('disabled'); } ... var delay1; rangesynth.oninput = function() { delay1 = rangesynth.va...
DeprecationReportBody - Web APIs
specifications specification status comment reporting apithe definition of 'deprecationreportbody' in that specification. editor's draft ...
...d(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; innerlistitem.textcontent = key + ': ' + keyvalue; innerlist.appendchild(innerlistitem); } } } the reports parameter contains an array of all the reports in the observer's report queue. we
loop over each report using a basic for
loop, then iterate over each entry of in the report's body (a deprecationreportbody instance) using a for...in structure, displaying each key/value pair inside a list item. specifications specification status comment reporting apithe definition of 'deprecationreportbody' in that specification. editor's draft ...
Using files from web applications - Web APIs
les selected by the user, each specified as a file object. you can determine how many files the user selected by checking the value of the file list's length attribute: const numfiles = filelist.length; individual file objects can be retrieved by simply accessing the list as an array: for (let i = 0, numfiles = filelist.length; i < numfiles; i++) { const file = filelist[i]; // ... } this
loop iterates over all the files in the file list. there are three attributes provided by the file object that contain useful information about the file. name the file's name as a read-only string. this is just the file name, and does not include any path information. size the size of the file in bytes as a read-only 64-bit integer. type the mime type of the file as a read-only string or "" i...
... } const img = document.createelement("img"); img.classlist.add("obj"); img.file = file; preview.appendchild(img); // assuming that "preview" is the div output where the content will be displayed. const reader = new filereader(); reader.onload = (function(aimg) { return function(e) { aimg.src = e.target.result; }; })(img); reader.readasdataurl(file); } } here our
loop handling the user-selected files looks at each file's type attribute to see if its mime type begins with the string "image/"). for each file that is an image, we create a new img element. css can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here. each image has the css class obj added to it, making it easy to find in the...
FileList - Web APIs
e list. return value the file representing the requested file. example this example iterates over all the files selected by the user using an input element: // fileinput is an html input element: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; //
loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } here is a complete example. <!doctype html> <html> <head> </head> <body> <!--multiple is set to allow multiple files to be selected--> <input id="myfiles" multiple type="file"> </body> <script> var pullfiles=function(){ // love the que...
... working draft html living standardthe ...
Gamepad.axes - Web APIs
he gamepad.axes property of the gamepad interface returns an array representing the controls with axes present on the device (e.g. analog thumb sticks).- each entry in the array is a floating point value in the range -1.0 – 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). ...
... specifications specification status comment gamepadthe definition of 'gamepad.axes' in that specification. working draft initial definition ...
Gamepad.buttons - Web APIs
and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. in this simple example i've just allowed either. ...
... specifications specification status comment gamepadthe definition of 'gamepad.buttons' in that specification. working draft initial definition ...
GamepadButton - Web APIs
and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. in this simple example i've just allowed either. ...
... working draft initial definition ...
HTMLCanvasElement.getContext() - Web APIs
lias: false, depth: false }); 2d context attributes: alpha: boolean that indicates if the canvas contains an alpha channel. if set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images. 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. this will force the use of a software (instead of hardware accelerated) 2d canvas and can save memory when calling getimagedata() frequently. this option is only available, if the flag gfx.canvas.willreadfrequently.enable is set to true (which, by default, is only the case for b2...
...t to true (which, by default, is only the case for b2g/firefox os). (blink only) storage: string that indicates which storage is used ("persistent" by default). webgl context attributes: alpha: boolean that indicates if the canvas contains an alpha buffer. 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. depth: boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. failifmajorperformancecaveat: boolean that indicates if a context will be created if the system performance is low or if no hardware gpu is available. powerpreference: a hint to the user agent indicating what configuratio...
HTMLMarqueeElement - Web APIs
the background color through color name or hexadecimal value. htmlmarqueeelement.direction sets the direction of the scrolling within the marquee. possible values are left, right, up and down. if no value is specified, the default value is left. htmlmarqueeelement.height sets the height in pixels or percentage value. htmlmarqueeelement.hspace sets the horizontal margin. htmlmarqueeelement.
loop sets the number of times the marquee will scroll. if no value is specified, the default value is −1, which means the marquee will scroll continuously. htmlmarqueeelement.scrollamount sets the amount of scrolling at each interval in pixels. the default value is 6. htmlmarqueeelement.scrolldelay sets the interval between each scroll movement in milliseconds. the default value is 85. note tha...
...t.vspace sets the vertical margin. htmlmarqueeelement.width sets the width in pixels or percentage value. event handlers htmlmarqueeelement.onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. htmlmarqueeelement.onfinish fires when the marquee has finished the amount of scrolling that is set by the
loop attribute. it can only fire when the
loop attribute is set to some number that is greater than 0. htmlmarqueeelement.onstart fires when the marquee starts scrolling. methods inherits methods from its parent, htmlelement. htmlmarqueeelement.start() starts scrolling of the marquee. htmlmarqueeelement.stop() stops scrolling of the marquee. examples <marquee>this text will scroll from r...
NodeList - Web APIs
ng the element as an argument to the function. nodelist.keys() returns an iterator, allowing code to go through all the keys of the key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0.) nodelist.values() returns an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection. example it's possible to
loop over the items in a nodelist using a for
loop: for (let i = 0; i < mynodelist.length; i++) { let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects. also, for..in is not guaranteed to visit the properties in any particular...
... a nodelist using a for
loop: for (let i = 0; i < mynodelist.length; i++) { let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects. also, for..in is not guaranteed to visit the properties in any particular order. for...of
loops will
loop over nodelist objects correctly: const list = document.queryselectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked = true; } recent browsers also support iterator methods (foreach()) as well as entries(), values(), and keys(). there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.querysele...
Report - Web APIs
specifications specification status comment reporting apithe definition of 'report' in that specification. editor's draft ...
... specifications specification status comment reporting apithe definition of 'report' in that specification. editor's draft ...
ScriptProcessorNode.bufferSize - Web APIs
ple the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to
loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = do...
...ata" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
ScriptProcessorNode.onaudioprocess - Web APIs
ple the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to
loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = do...
...ata" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
ScriptProcessorNode - Web APIs
les the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to
loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = do...
...ata" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
StylePropertyMapReadOnly.entries() - Web APIs
syntax stylepropertymapreadonly.entries() parameters none. return value an array of the given stylepropertymapreadonly object's own enumerable property [key, value] pairs. ...
... syntax stylepropertymapreadonly.entries() parameters none. return value an array of the given stylepropertymapreadonly object's own enumerable property [key, value] pairs. ...
Simple color animation - Web APIs
ple illustration of color animation with webgl, as well as user interaction. the user can start, stop and restart the animation by clicking the button. this time we put the webgl function calls within a timer event handler. a click event handler additionally enables the basic user interaction of starting and stopping the animation. the timer and the timer handler function establish the animation
loop, a set of drawing commands that are executed at a regular period (typically, every frame; in this case, once per second). <p>a simple webgl program that shows color animation.</p> <p>you can click the button below to toggle the color animation on or off.</p> <canvas id="canvas-view">your browser does not seem to support html5 canvas.</canvas> <button id="animation-onoff"> press here ...
...e to hold a timer that drives the animation. var timer; // click event handlers. var button = document.queryselector("#animation-onoff"); var verb = document.queryselector("strong"); function startanimation(evt) { button.removeeventlistener(evt.type, startanimation, false); button.addeventlistener("click", stopanimation, false); verb.innerhtml="stop"; // setup animation
loop by redrawing every second. timer = setinterval(drawanimation, 1000); // give immediate feedback to user after clicking, by // drawing one animation frame. drawanimation(); } function stopanimation(evt) { button.removeeventlistener(evt.type, stopanimation, false); button.addeventlistener("click", startanimation, false); verb.innerhtml="start"; // stop animation ...
Animating textures in WebGL - Web APIs
ml's <head>. ...
...unction() { playing = true; checkready(); }, true); video.addeventlistener('timeupdate', function() { timeupdate = true; checkready(); }, true); video.src = url; video.play(); function checkready() { if (playing && timeupdate) { copyvideo = true; } } return video; } first we create a video element. we set it to autoplay, mute the sound, and
loop the video. we then set up two events to make sure the video is playing and the time has been updated. we need both of these checks because it will produce an error if you upload a video to webgl that has no data available yet. checking for both of these events guarantees there is data available and it's safe to start uploading video to a webgl texture. in the code above, we confirm whether we got...
Movement, orientation, and motion: A WebXR example - Web APIs
ing the event handler directly, we complete the close-out process manually in this situation. starting up the webxr session the sessionstarted() function handles actually setting up and starting the session, by setting up event handlers, compiling and installing the glsl code for the vertex and fragment shaders, and attaching the webgl layer to the webxr session before kicking off the rendering
loop. it gets called as the handler for the promise returned by issessionsupported(). function sessionstarted(session) { let refspacetype; xrsession = session; xrbutton.innertext = "exit webxr"; xrsession.addeventlistener("end", sessionended); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); if (allowmouserotation) { canvas.a...
... visually presenting the frame both on the xr device and on the screen. to ensure that the on-screen canvas is the right size to allow us to do this, we set its width to be equal to the individual xrview width multiplied by the number of views; the canvas height is always the same as the viewport's height. the two lines of code that adjust the canvas size are not needed in regular webxr rendering
loops. applying the user inputs the applyviewercontrols() function, which is called by drawframe() before beginning to render anything, takes the offsets in each of the three directions, the yaw offset, and the pitch offset as recorded by the handlekeydown() and handlepointermove() functions in response to the user pressing keys and dragging their mouse with the right mouse button pressed. it take...
Controlling multiple parameters with ConstantSourceNode - Web APIs
f the constantsourcenode.offset parameter. you may have times when you want to have multiple audio parameters be linked so they share the same value even while being changed in some way. for example, perhaps you have a set of oscillators, and two of them need to share the same, configurable volume, or you have a filter that's been applied to certain inputs but not to all of them. ...
...e a set of oscillators, and two of them need to share the same, configurable volume, or you have a filter that's been applied to certain inputs but not to all of them. you could use a
loop and change the value of each affected audioparam one at a time, but there are two drawbacks to doing it that way: first, that's extra code that, as you're about to see, you don't have to write; and second, that
loop uses valuable cpu time on your thread (likely the main thread), and there's a way to offload all that work to the audio rendering thread, which is optimized for this kind of work and may run at a more appropriate priority level than your code. the solution is simple, and it involves using an audio node type which, at first glance, doesn't look all that useful: constantsourcenode. the technique ...
window.requestIdleCallback() - Web APIs
the window.requestidlecallback() method queues a function to be called during a browser's idle periods. this enables developers to perform background and low priority work on the main event
loop, without impacting latency-critical events such as animation and input response. functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. you can call requestidlecallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event
loop. a timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. synta...
...required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. syntax var handle = window.requestidlecallback(callback[, options]) return value an id which can be used to cancel the callback by passing it into the window.cancelidlecallback() method. parameters callback a reference to a function that should be called in the near future, when the event
loop is idle. the callback function is passed an idledeadline object describing the amount of time available and whether or not the callback has been run because the timeout period expired. options optional contains optional configuration parameters. currently only one property is defined: timeout: if timeout is specified and has a positive value, and the callback has not already been called by ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the queuemicrotask() method, which is exposed on the window or worker interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event
loop. the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event
loop. this lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to p...
...nal cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event
loop. return value undefined. examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => ...
WorkerGlobalScope - Web APIs
the workerglobalscope interface of the web workers api is an interface representing the scope of any worker. workers have no browsing context; this scope contains the information usually conveyed by window objects — in this case event handlers, the console or the associated workernavigator object. each workerglobalscope has its own event
loop. this interface is usually specialized by each worker type: dedicatedworkerglobalscope for dedicated workers, sharedworkerglobalscope for shared workers, and serviceworkerglobalscope for serviceworker. the self property returns the specialized scope for each context. properties this interface inherits properties from the eventtarget interface and windoworworkerglobalscope and windoweventhandlers mixins. standard properties workerglobalscope.naviga...
...h() starts the process of fetching a resource from the network. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. windoworworkerglobalscope.settimeout() schedules a function to execute in a given amount of time. deprecated methods workerglobalscope.close() discards any tasks queued in the workerglobalscope's event
loop, effectively closing this particular scope. in newer browser versions, close() is available on dedicatedworkerglobalscope and sharedworkerglobalscope instead. this change was made to stop close() being available on service workers, as it isn't supposed to be used there and always throws an exception when called (see bug 1336043). example you won't access workerglobalscope directly in your code...
XRSession.requestAnimationFrame() - Web APIs
rn that ensures seamless transition between non-immersive animations created via window.requestanimationframe and immersive xr animations. let xrsession = null function onwindowanimationframe(time) { window.requestanimationframe(onwindowanimationframe) // this may be called while an immersive session is running on some devices, // such as a desktop with a tethered headset. to prevent two
loops from // rendering in parallel, skip drawing in this one until the session ends. if (!xrsession) { renderframe(time, null) } } // the window animation
loop can be started immediately upon the page loading. window.requestanimationframe(onwindowanimationframe) function onxranimationframe(time, xrframe) { xrsession.requestanimationframe(onxranimationframe) renderframe(time, xrframe) ...
...frame) } function renderframe(time, xrframe) { // shared rendering logic. } // assumed to be called by a user gesture event elsewhere in code. function startxrsession() { navigator.xr.requestsession('immersive-vr').then((session) => { xrsession = session xrsession.addeventlistener('end', onxrsessionended) // do necessary session setup here. // begin the session’s animation
loop. xrsession.requestanimationframe(onxranimationframe) }) } function onxrsessionended() { xrsession = null } specifications specification status comment webxr device apithe definition of 'xrsession.requestanimationframe' in that specification. working draft initial definition. ...
Using CSS animations - CSS: Cascading Style Sheets
ener() function, which is shown below. function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time is " + event.elapsedtime; break; case "animationend": l.innerhtml = "ended: elapsed time is " + event.elapsedtime; break; case "animationiteration": l.innerhtml = "new
loop started at time " + event.elapsedtime; break; } document.getelementbyid("output").appendchild(l); } this code, too, is very simple. it simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we’re using to log these events. the output, when all is said and done, looks something like this: star...
...lapsedtime; break; } document.getelementbyid("output").appendchild(l); } this code, too, is very simple. it simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we’re using to log these events. the output, when all is said and done, looks something like this: started: elapsed time is 0 new
loop started at time 3.01200008392334 new
loop started at time 6.00600004196167 ended: elapsed time is 9.234000205993652 note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured. note also that after the final iteration of the animation, the animationiteration event isn’t sent; instead, the animationend event is sent. ...
Overview of events and handlers - Developer guides
n the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. the displayed page remains unchanged until the browser requests a new page. with the change to dynamic page rendering, browsers
loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the html content of a page, the interaction of a user with the contents of the page e...
...nt of a page, the interaction of a user with the contents of the page e.g., clicks a button. douglas crockford explains this change effectively in several lectures, notably his talk, an inconvenient api: the theory of the dom, which shows the change in flow from the original browser flow to the event driven browser. the latter approach changes the last steps from a single flow into a perpetual
loop, where waiting for and handling the incidence of new events follows painting. the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all execution env...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
e to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the above example shows simple usage of the <audio> element. in a similar manner to the <img> element, we include a path to the media we want to embed inside the src attribute; we can include other attributes to specify information such as whether we want it to autoplay and
loop, whether we want to show the browser's default audio controls, etc. the content inside the opening and closing <audio></audio> tags is shown as a fallback in browsers that don't support the element. attributes this element's attributes include the global attributes. autoplay a boolean attribute: if specified, the audio will automatically begin playback as soon as it can do so, without wait...
...ion read only a double-precision floating-point value which indicates the duration (total length) of the audio in seconds, on the media's timeline. if no media is present on the element, or the media is not valid, the returned value is nan. if the media has no known end (such as for live streams of unknown duration, web radio, media incoming from webrtc, and so forth), this value is +infinity.
loop a boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio. muted a boolean attribute that indicates whether the audio will be initially silenced. its default value is false. preload this enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience. it...
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
plorer only html background sound element (<bgsound>) sets up a sound file to play in the background while the page is used; use <audio> instead. do not use this! in order to embed audio in a web page, you should be using the <audio> element. attributes balance this attribute defines a number between -10,000 and +10,000 that determines how the volume will be divided between the speakers.
loop this attribute indicates the number of times a sound is to be played and either has a numeric value or the keyword infinite. src this attribute specifies the url of the sound file to be played, which must be one of the following types: .wav, .au, or .mid. volume this attribute defines a number between -10,000 and 0 that determines the loudness of a page's background sound. example <bgsoun...
... a sound is to be played and either has a numeric value or the keyword infinite. src this attribute specifies the url of the sound file to be played, which must be one of the following types: .wav, .au, or .mid. volume this attribute defines a number between -10,000 and 0 that determines the loudness of a page's background sound. example <bgsound src="sound1.mid"> <bgsound src="sound2.au"
loop="infinite"> usage notes historically, the <embed> element could be used with audio player plug-ins to play audio in the background in most browsers. however, even this is no longer appropriate, and you should use <audio> instead, since it's more capable, more compatible, and doesn't require plug-ins. you can write <bgsound> as a self-closing tag (<bgsound />); however, since this element is n...
<input type="file"> - HTML: Hypertext Markup Language
e latter two styles to mean the file input isn't interactive. next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). the event listener invokes our custom updateimagedisplay() function. ...
...things to note here: we use the custom validfiletype() function to check whether the file is of the correct type (e.g. the image types specified in the accept attribute). if it is, we: print out its name and file size into a list item inside the previous <div> (obtained from file.name and file.size). ...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
ernate. if no value is specified, the default value is scroll. bgcolor sets the background color through color name or hexadecimal value. direction sets the direction of the scrolling within the marquee. possible values are left, right, up and down. if no value is specified, the default value is left. height sets the height in pixels or percentage value. hspace sets the horizontal margin
loop sets the number of times the marquee will scroll. if no value is specified, the default value is −1, which means the marquee will scroll continuously. scrollamount sets the amount of scrolling at each interval in pixels. the default value is 6. scrolldelay sets the interval between each scroll movement in milliseconds. the default value is 85. note that any value smaller than 60 is ignored...
...ose values are not ignored. vspace sets the vertical margin in pixels or percentage value. width sets the width in pixels or percentage value. event handlers onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. onfinish fires when the marquee has finished the amount of scrolling that is set by the
loop attribute. it can only fire when the
loop attribute is set to some number that is greater than 0. onstart fires when the marquee starts scrolling. methods start() starts scrolling of the marquee. stop() stops scrolling of the marquee. examples <marquee>this text will scroll from right to left</marquee> <marquee direction="up">this text will scroll from bottom to top</marquee> <marq...
<video>: The Video Embed element - HTML: Hypertext Markup Language
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the above example shows simple usage of the <video> element. in a similar manner to the <img> element, we include a path to the media we want to display inside the src attribute; we can include other attributes to specify information such as video width and height, whether we want it to autoplay and
loop, whether we want to show the browser's default video controls, etc. the content inside the opening and closing <video></video> tags is shown as a fallback in browsers that don't support the element. attributes like all other html elements, this element supports the global attributes. autoplay a boolean attribute; if specified, the video automatically begins to play back as soon as it can d...
...o's display area, in css pixels (absolute values only; no percentages.) intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute. specifically, the image would raster at these dimensions and naturalwidth/naturalheight on images would return the values specified in this attribute. explainer, examples
loop a boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video. muted a boolean attribute that indicates the default setting of the audio contained in the video. if set, the audio will be initially silenced. its default value is false, meaning that the audio will be played when the video is played. playsinline a boolean attribute i...
JavaScript data types and data structures - JavaScript
attributes of a data property attribute type description default value [[value]] any javascript type the value retrieved by a get access of the property. undefined [[writable]] boolean if false, the property's [[value]] cannot be changed. false [[enumerable]] boolean if true, the property will be enumerated in for...in
loops. see also enumerability and ownership of properties. false [[configurable]] boolean if false, the property cannot be deleted, cannot be changed to an accessor property, and attributes other than [[value]] and [[writable]] cannot be changed. false obsolete attributes (as of ecmascript 3, renamed in ecmascript 5) attribute type description ...
...henever a get access to the value is performed. see also get. undefined [[set]] function object or undefined the function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. see also set. undefined [[enumerable]] boolean if true, the property will be enumerated in for...in
loops. false [[configurable]] boolean if false, the property can't be deleted and can't be changed to a data property. false "normal" objects, and functions a javascript object is a mapping between keys and values. keys are strings (or symbols), and values can be anything. this makes objects a natural fit for hashmaps. functions are regular objects with the additional cap...
Using Promises - JavaScript
t promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call. this convention has several advantages. we will explore each one. guarantees unlike old-fashioned passed-in callbacks, a promise comes with some guarantees: callbacks will never be called before the completion of the current run of the javascript event
loop. callbacks added with then(), as above, will be called even after the success or failure of the asynchronous operation. multiple callbacks may be added by calling then() several times. each callback is executed one after another, in the order in which they were inserted. one of the great things about using promises is chaining. chaining a common need is to execute two or more asynchronous o...
...pretty soon: const wait = ms => new promise(resolve => settimeout(resolve, ms)); wait().then(() => console.log(4)); promise.resolve().then(() => console.log(2)).then(() => console.log(3)); console.log(1); // 1, 2, 3, 4 nesting simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition. see common mistakes. nesting is a control structur...
Array.prototype.every() - JavaScript
44].every(x => x >= 10); // true​ affecting initial array (modifying, appending, and deleting) the following examples tests the behaviour of the every method when the array is modified. ...
...
loop runs for 3 iterations, but would // have run 2 iterations without any modification // // 1st iteration: [1,1,3,4][0] -> 1 // 2nd iteration: [1,1,2,4][1] -> 1 // 3rd iteration: [1,1,2,3][2] -> 2 // --------------- // appending items // --------------- arr = [1, 2, 3]; arr.every( (elem, index, arr) => { arr.push('new') console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) //
loop runs for 3 iterations, even after appending new items // // 1st iteration: [1, 2, 3, new][0] -> 1 // 2nd iteration: [1, 2, 3, new, new][1] -> 2 // 3rd iteration: [1, 2, 3, new, new, new][2] -> 3 // --------------- // deleting items // --------------- arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr.pop() console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) //
loop run...
Array.prototype.shift() - JavaScript
in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ec...
...('myfish before:', json.stringify(myfish)); // myfish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myfish.shift(); console.log('myfish after:', myfish); // myfish after: ['clown', 'mandarin', 'surgeon'] console.log('removed this element:', shifted); // removed this element: angel using shift() method in while
loop the shift() method is often used in condition inside while
loop. in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ecma-262)the definition of 'array.prototype.shift' in that specific...
Array.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array. syntax arr.values() return value a new array iterator object. examples iteration using for...of
loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator]. array.prototype.values === array.prototype[symbol.iterator] //true iteration using .next() var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // objec...
...see iteration protocols. value: there are no values stored in the array iterator object; instead it stores the address of the array used in its creation and so depends on the values stored in that array. var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); console.log(iterator); // array iterator { } iterator.next().value; // "a" arr[1]='n'; iterator.next().val...
Function.prototype.apply() - JavaScript
ush, it will actually add that array as a single element, instead of adding the elements individually. so you end up with an array inside an array. what if that is not what you want? concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and returns a new array. but you wanted to append to the existing array... so what now? write a
loop? surely not? apply to the rescue! const array = ['a', 'b']; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] using apply and built-in functions clever usage of apply allows you to use built-in functions for some tasks that would probably have otherwise been written by
looping over the array values. as an example, here are math.max/ma...
...oping over the array values. as an example, here are math.max/math.min, used to find out the maximum/minimum value in an array. // min/max number in an array const numbers = [5, 6, 2, 3, 7]; // using math.min/math.max apply let max = math.max.apply(null, numbers); // this about equal to math.max(numbers[0], ...) // or math.max(5, 6, ...) let min = math.min.apply(null, numbers); // vs. simple
loop based algorithm max = -infinity, min = +infinity; for (let i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } but beware: by using apply this way, you run the risk of exceeding the javascript engine's argument length limit. the consequences of applying a function with too many arguments (that is, more than...
Map - JavaScript
key equality key equality is based on the samevaluezero algorithm. nan is considered the same as nan (even though nan !== nan) and all other values are considered equal according to the semantics of the === operator. ...
...n can also be used as a key. ...
Object.defineProperty() - JavaScript
or symbol of the property to be defined or modified. descriptor the descriptor for the property being defined or modified. return value the object that was passed to the function. description this method allows a precise addition to or modification of a property on an object. normal property addition through assignment creates properties which show up during property enumeration (for...in
loop or object.keys method), whose values may be changed, and which may be deleted. this method allows these extra details to be changed from their defaults. by default, values added using object.defineproperty() are immutable and not enumerable. property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. a data descriptor is a property that has a valu...
...-only return o.b; // returns 2 without the line above }()); as seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either. enumerable attribute the enumerable property attribute defines whether the property is picked by object.assign() or spread operator. for non-symbols properties it also defines whether it shows up in a for...in
loop and object.keys() or not. var o = {}; object.defineproperty(o, 'a', { value: 1, enumerable: true }); object.defineproperty(o, 'b', { value: 2, enumerable: false }); object.defineproperty(o, 'c', { value: 3 }); // enumerable defaults to false o.d = 4; // enumerable defaults to true // when creating a property by setting it object.defineproperty(o, symbol.for('e'), { value: 5,...
Object.entries() - JavaScript
the order of the array returned by object.entries() does not depend on how an object is defined. if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));. the source for this interactive example is stored in a github repository. ...
...string-keyed property [key, value] pairs are to be returned. return value an array of the given object's own enumerable string-keyed property [key, value] pairs. description object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object. the ordering of the properties is the same as that given by
looping over the property values of the object manually. polyfill to add compatible object.entries() support in older environments that do not natively support it, you can use any of the following: a demonstration implementation of object.entries in the tc39/proposal-object-values-entries (if you don't need any support for ie); a polyfill in the es-shims/object.entries repositories; or, you can...
Object.getOwnPropertyNames() - JavaScript
eturn value an array of strings that corresponds to the properties found directly in the given object. description object.getownpropertynames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. the ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in
loop (or by object.keys()) over the properties of the object. the ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined. in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be coerced to an object. object.getownpropertynames('foo'); // typeerror: "...
... items on the prototype chain are not listed: function parentclass() {} parentclass.prototype.inheritedmethod = function() {}; function childclass() { this.prop = 5; this.method = function() {}; } childclass.prototype = new parentclass; ...
Object.keys() - JavaScript
the object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal
loop would. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.keys(obj) parameters obj the object of which the enumerable's own properties are to be returned. return value an array of strings that represent all the enumerable properties of the given object. ...
...j) parameters obj the object of which the enumerable's own properties are to be returned. return value an array of strings that represent all the enumerable properties of the given object. description object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. the ordering of the properties is the same as that given by
looping over the properties of the object manually. polyfill to add compatible object.keys support in older environments that do not natively support it, copy the following snippet: // from /docs/web/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = (function() { 'use strict'; var hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !(...
Object.values() - JavaScript
if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.values(obj) parameters obj the object whose enumerable own property values are to be returned. ...
...us a pull request. syntax object.values(obj) parameters obj the object whose enumerable own property values are to be returned. return value an array containing the given object's own enumerable property values. description object.values() returns an array whose elements are the enumerable property values found on the object. the ordering of the properties is the same as that given by
looping over the property values of the object manually. polyfill to add compatible object.values support in older environments that do not natively support it, you can find a polyfill in the tc39/proposal-object-values-entries or in the es-shims/object.values repositories. examples using object.values const obj = { foo: 'bar', baz: 42 }; console.log(object.values(obj)); // ['bar', 42] // array...
String.prototype.charAt() - JavaScript
ring.charat(999) + "'"); these lines display the following: the character at index 0 is 'b' the character at index 0 is 'b' the character at index 1 is 'r' the character at index 2 is 'a' the character at index 3 is 'v' the character at index 4 is 'e' the character at index 999 is '' getting whole characters the following provides a means of ensuring that going through a string
loop always provides a whole character, even if the string contains characters that are not in the basic multi-lingual plane. var str = 'a \ud87e\udc04 z'; // we could also use a non-bmp character directly for (var i = 0, chr; i < str.length; i++) { if ((chr = getwholechar(str, i)) === false) { continue; } // adapt this line at the top of each
loop, passing in the whole string and // the ...
...he following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automatically (if the character warrants it in being a surrogate pair). ...
String.prototype.charCodeAt() - JavaScript
ex. the iso-latin-1 codeset ranges from 0 to 255. the first 0 to 127 are a direct match of the ascii character set. examples using charcodeat() the following example returns 65, the unicode value for a. 'abc'.charcodeat(0) // returns 65 fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the string is unknown this version might be used in for
loops and the like when it is unknown whether non-bmp characters exist before the specified index position. function fixedcharcodeat(str, idx) { // ex. fixedcharcodeat('\ud800\udc00', 0); // 65536 // ex. fixedcharcodeat('\ud800\udc00', 1); // false idx = idx || 0; var code = str.charcodeat(idx); var hi, low; // high surrogate (could change last hex to 0xdb7f // to treat high private su...
...le characters) if (0xd800 <= code && code <= 0xdbff) { hi = code; low = str.charcodeat(idx + 1); if (isnan(low)) { throw 'high surrogate not followed by ' + 'low surrogate in fixedcharcodeat()'; } return ( (hi - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000; } if (0xdc00 <= code && code <= 0xdfff) { // low surrogate // we return false to allow
loops to skip // this iteration since should have already handled // high surrogate above in the previous iteration return false; // hi = str.charcodeat(idx - 1); // low = code; // return ((hi - 0xd800) * 0x400) + // (low - 0xdc00) + 0x10000; } return code; } fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the strin...
String.prototype.matchAll() - JavaScript
obj is passed, it is implicitly converted to a regexp by using new regexp(obj). the regexp object must have the /g flag, otherwise a typeerror will be thrown. return value an iterator (which is not a restartable iterable). ...
... instead, by using matchall, you get an iterator to use with the more convenient for...of, array spread, or array.from() constructs: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; const matches = str.matchall(regexp); for (const match of matches) { console.log(`found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`); } /...
Comma operator (,) - JavaScript
the comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. this lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. this is commonly used to provide multiple parameters to a for
loop. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax expr1, expr2, expr3... parameters expr1, expr2, expr3... one or more expressions, the last of which is returned as the value of the compound expression. usage notes you can use the c...
...l request. syntax expr1, expr2, expr3... parameters expr1, expr2, expr3... one or more expressions, the last of which is returned as the value of the compound expression. usage notes you can use the comma operator when you want to include multiple expressions in a location that requires a single expression. the most common usage of this operator is to supply multiple parameters in a for
loop. the comma operator is fully different from the comma within arrays, objects, and function arguments and parameters. examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once. the following code prints the values of the diagonal elements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) conso...
empty - JavaScript
ve-examples and send us a pull request. syntax ; description the empty statement is a semicolon (;) indicating that no statement will be executed, even if javascript syntax requires one. the opposite behavior, where you want multiple statements, but javascript only allows a single one, is possible using a block statement, which combines several statements into a single one. ...
...escription the empty statement is a semicolon (;) indicating that no statement will be executed, even if javascript syntax requires one. the opposite behavior, where you want multiple statements, but javascript only allows a single one, is possible using a block statement, which combines several statements into a single one. examples empty
loop body the empty statement is sometimes used with
loop statements. see the following example with an empty
loop body: let arr = [1, 2, 3]; // assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] unintentional usage it is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon. in the following e...
continue - JavaScript
the continue statement terminates execution of the statements in the current iteration of the current or labeled
loop, and continues execution of the
loop with the next iteration. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax continue [label]; label identifier associated with the label of the statement. description in contrast to the break statement, continue does not terminate the execution of the
loop entirely: instead, in a while
loop, it jumps back to the condition. in a for
loop, it jumps to the update expression. the continue statement can include an optional label that allows the pro...
...ier associated with the label of the statement. description in contrast to the break statement, continue does not terminate the execution of the
loop entirely: instead, in a while
loop, it jumps back to the condition. in a for
loop, it jumps to the update expression. the continue statement can include an optional label that allows the program to jump to the next iteration of a labeled
loop statement instead of the current
loop. in this case, the continue statement needs to be nested within this labeled statement. examples using continue with while the following example shows a while
loop that has a continue statement that executes when the value of i is 3. thus, n takes on the values 1, 3, 7, and 12. var i = 0; var n = 0; while (i < 5) { i++; if (i === 3) { continue; ...
JavaScript
ers some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", along with discussing key javascript features such as variables, strings, numbers, and arrays. javascript building blocks continues our coverage of javascript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements,
loops, functions, and events. introducing javascript objects the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. asynchronous javascript discusses asynchronous javascript, why it is important, and how it can be used to effectively handle pot...
...inheritance. strict mode strict mode defines that you can not use any variable before initializing it. it is a restricted variant of ecmascript 5, for faster performance and easier debugging. javascript typed arrays javascript typed arrays provide a mechanism for accessing raw binary data. memory management memory life cycle and garbage collection in javascript. concurrency model and event
loop javascript has a concurrency model based on an "event
loop". reference browse the complete javascript reference documentation. standard objects get to know standard built-in objects array, boolean, date, error, function, json, math, number, object, regexp, string, map, set, weakmap, weakset, and others. expressions and operators learn more about the behavior of javascript's operators ...
test/httpd - Archive of obsolete content
be used in unit tests. 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. }) }); this starts a server in background (assuming you're running this code in an application that has an event
loop, such as firefox). the server listens at http://localhost:port/ and serves files from the specified directory. you can serve static content or use sjs scripts, as described in documentation on developer.mozilla.org. you can also use nshttpserver to start the server manually: var { nshttpserver } = require("sdk/test/httpd"); var srv = new nshttpserver(); // further documentation on developer.moz...
util/collection - Archive of obsolete content
a scalar value empties the collection and adds the value. setting it to an array empties the collection and adds all the items in the array. parameters object : object the property will be defined on this object. propname : string the name of the property. backingarray : array if given, this will be used as the collection's backing array. collection a collection object provides for...in-
loop iteration. items are yielded in the order they were added. for example, the following code... var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mu...
xml:base support in old browsers - Archive of obsolete content
stindexof('/')-1); if (link.lastindexof('/') !== link.length-1) { link += '/'; } link = loc.protocol + '//' + loc.host + dirpath + link; } } return link; } function getxmlbase (thisitem) { // fix: need to keep going up the chain if still a relative url!!!!! ...
Default Preferences - Archive of obsolete content
erences must be in very particular spot: | extension root +--|content +--|skin +--|defaults +--|preferences to add preferences simply drop a .js file into that directory and mozilla will read it and set the appropriate preferences. the actual file, despite having .js extension, is not a javascript file. you may not set variables inside of it, nor may do any kind of program flow control (ifs,
loops etc.) nor even calculated values (i.e. 3600 * 24 * 5). doing so will cause mozilla to stop processing your preferences file without any notification, warning, error, or exception. think of it more as an .ini file. comments are perfectly acceptable. inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.example.int', 1); pref(...
Enhanced Extension Installation - Archive of obsolete content
t higher locations. when an item is uninstalled, the extension manager checks the startup cache to see if there is another copy of the item installed at a lower install location. if there is one, then the item is uninstalled and an entry is added to the pending operations list that indicates the item at the lower install location needs to be installed. the install operation finalization process
loops continuously installing, upgrading and uninstalling items at progressively lower locations until the size of the pending operations list is finally zero. little things this upgrade fixes or changes it used to not be possible to move items in the extension manager ui up and down if there were items that were from two different install locations in the list - that is there were actually two rdf ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
ver, now there's a considerable store of knowledge. because firefox and its extensions are designed to support multiple languages, excellent extensions come from all over the world, and can be quickly localized by anyone interested. this lowers the threshold both to using and to developing extensions; that fact, combined with firefox's rapidly growing popularity, has created a positive feedback
loop, with the number of extension users and extension developers growing explosively—there are now more than 7000 extensions and themes published at the firefox add-ons site (https://addons.mozilla.org). what you can do with extensions let's look at what features extensions can add, and some actual examples of extensions. single feature extensions fixme: update this. these are relatively simpl...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
ad", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() returns a new function. this is important to know in particular when you later want to call removeeventlistener: you'll have to pass the resulting function from the first .bind() call. calling .bind() again with removeeventlistener will not work. also, calling .bind() in a tight (inner)
loop should be avoided for performance reasons, as calling .bind() does require some work and memory. overriding/extending/amending existing functions a common thing add-ons do during their initialization is overriding/extending existing browser functions by using function.tostring/function.tosource and eval to "string-patch" the function body. // do not use! var functionbody = gbrowser.addtab.tos...
Appendix D: Loading Scripts - Archive of obsolete content
asynchronously in their own threads, which means that they have limited risk of interfering with the main thread. they may safely perform synchronous xmlhttprequests or other intensive computation which would normally need to be broken up into multiple callbacks. safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event
loop, there are significant safety advantages over other methods of asynchronous execution. disadvantages limited scoping: as data from the main thread may only be accessed via json message passing, there are significant difficulties in performing many operations in worker scopes. dom access: as there is no dom access in worker scopes, xmlhttprequests may not easily be used with xml or html sour...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
tories. our management also has to accept the fact that some older or smaller browsers may be getting an un-styled version of our content. we know that some users may prefer getting an un-styled version, because they'll finally be able to read our content in the browser they use. but some users may write in, frustrated and complaining about the horrible design decisions we've made. those feedback
loops will have to be managed appropriately. for wired news, we analyzed the traffic reports to get a picture of our user base. from looking at our data, we predict there could be as much as 14% of our users who will get the un-styled version of our content. that's a significant percentage when we're used to our pages looking the same in every browser. were there any other lessons you learned during...
DOMSubtreeModified - Archive of obsolete content
example the following code will display the time of last dom change on the title bar of the page. this event has been deprecated in favor of the mutation observer api this event can cause infinite
loops if you decide to change the dom inside the event handler, hence it has been disabled in a number of browsers (see domattrmodified and domsubtreemodified events are no longer fired when style attribute is changed via cssom for example). document.body.addeventlistener('domsubtreemodified', function () { document.title = 'dom changed at ' + new date(); }, false); ...
Index - Archive of obsolete content
istent way to do that. 3712 writing a plugin for mac os x add-ons, gecko, npapi, plugins this article is adapted from josh aas's blog post writing an npapi plugin for mac os x. 3713 xembed extension for mozilla plugins add-ons, plugins recent versions of mozilla include an extension for writing plugins that use xembed instead of using the old xt-based main
loop that most plugins have been using since the netscape 3.x days. 3714 rss rss really simple syndication (rss) is a popular html-like xml-based data format used for syndication. rss has a sordid history and a multitude of different incompatible rss versions. (some being based on rdf, but most only being based on xml.) nonetheless, rss is an extremely popular format that is used ...
MMgc - Archive of obsolete content
the live objects and mark them. this is the part of the gc work that takes the most time and the part that needs to be incrementalized. in order to incrementalize marking it needs to be a process that can be stopped and started. our marking algorithm is a conservative marking algorithm that makes marking automatic, there are no mark() methods the gc engine needs to call, marking is simply a tight
loop that processes a queue. the way it works is that all gc roots are registered with the gc library and it can mark everything by traversing the roots. at the beginning all the gc roots are pushed onto the work queue. items on the queue are conservatively marked and unmarked gc pointers discovered while processing each item are pushed on to the queue. when the queue is empty all the marking is compl...
Monitoring WiFi access points - Archive of obsolete content
the first thing the code above does is to prototype the listener object that will be receiving notifications of changes to the access point list. this object is described in lines 11 through 40 in the code above. the onchange() method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points. then the
loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div. then the c div is updated with the number of times the list has been refreshed. the onerror() method simply opens an alert that displays the error code received. starting to monitor access points to start monitoring the access points, we instantiate the listener (on line...
Source code directories overview - Archive of obsolete content
code and command line tools for implementing the basic machinery of xpcom components (which stands for "cross platform component object model"). xpcom is the mechanism that allows mozilla to export interfaces and have them automatically available to javascript scripts, to microsoft com and to regular mozilla c code. some low-level xpcom classes and interfaces are also defined here (e.g. the event
loop for all platforms). xpcom is compatible and very similar to microsoft com (although xpcom is cross-platform). xpfe contains the c interfaces, c code and xul for implementing the "cross platform front end." essentially, this is where the mozilla program starts and manages other components to accomplish tasks. this code contains very little platform dependent code; it relies on other components to...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
install a new control on operating systems such as windows nt, 2000 & xp. usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2" width="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="
loop" value="true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting control, the width and height specify the dimensions in pixels. you may optionally specify a codebase attribute if you have packaged the control into a cab file and wish for it to be installed automatically. the following <embed> attributes have <param> tag equivalents: <param name="type" ...
Creating a hybrid CD - Archive of obsolete content
latest versions of cdrecord. i used version 1.8.1a03 although you'll probably want to get a newer one. here's what i did to create the cd for the second anniversary party. mkhybrid -o ~/party.iso -r -j -hfs -v mozilla.party -map ~/hfsmapping ~/party/ cdrecord -v speed=2 dev=0,6,0 ~/party.iso its also handy to be able to mount an image file to test it. mount ~/party.iso /mnt/cdrom -t iso9660 -o
loop=/dev/
loop3,blocksize=1024 umount /mnt/cdrom here is the hfs mapping that i used. the creator "moss" is for netscape 4.x and "mozz" is used for mozilla. it is used as the creator type for readme and other text files because it can handle unix and windows linebreaks, but teachtext cannot. # example filename mapping file used by mkhybrid for hfs # # extn xlate creator type comment .hqx ...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
in order to communicate with xpcom after this point, you should use an nsiproxyobjectmanager. following on from the above example, to create a new window, we would do the following: // first, get the event queue service. this handles all event queues in xpcom. nsieventqueueservice eventqueueservive = (nsieventqueueservice)servicemanager.getser...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
listener if it claims to handle the data, as well as hooking up a stream converter if the listener asks for one. if any of those steps fails, the function returns false so that another content listener will be looked for. the first content listener we check is the content listener associated with our window context (the docshell that initiated the load). if this can't handle the content type, we
loop over our stored list of possible listeners (previously registered via registercontentlistener) and ask each one in turn whether it can handle the data. if we still have not found an nsiuricontentlistener, we ask the category manager whether it has an entry for the desired content type under the ns_content_listener_categorymanager_entry key. if it does, we instantiate that component using its co...
Metro browser chrome tests - Archive of obsolete content
etup(), teardown(), and run() each have individual exception handlers to prevent one method from interfering with the execution of another. an exception in any of these methods will cause a test failure. additional built-in framework test checks will run after the completion of each individual test insuring tests clean up properly. for more information on test execution see the main test exectuon
loop in head.js. adding a new browser chrome test to the tree to add a new metro browser chrome test add the test file to the browser_tests variable in /browser/metro/base/tests/mochitest/makefile.in. your test file name must be prefixed with "browser_", and must have a file extension of ".js". files that don't match this pattern will be ignored by the test harness. using a descriptive file name is st...
Monitoring downloads - Archive of obsolete content
cell.setattribute("style", style); row.appendchild(cell); loglist.appendchild(row); } } finally { statement.reset(); dbconn = null; } } this code is fairly simple. it starts by opening the sqlite database containing the log information, then creates a select sql statement to pull all entries from the database. to iterate over the results, we use a while
loop that calls the mozistoragestatement object's executestep() method. each time that method is called, one row of the results is fetched. after that, the list row object is created, and each entry in the search result is fetched and inserted into the appropriate list cell. the interesting bits to take away from this: mozistoragestatement has several data getter routines for fetching search resu...
Tuning Pageload - Archive of obsolete content
fore the delay expires. the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the event
loop, which allows layout and painting to happen. if the parser gets a large chunk of data, it will try to parse it all, building the corresponding content model. since layout and painting happen asynchronously, while the parser is working there is no layout or painting. so this preference is used to increase responsiveness, especially on cached loads (where data comes into the parser in large chunks...
URIs and URLs - Archive of obsolete content
. noteable differences necko does not support certain deprecated forms of relative urls, based on the following part of rfc 2396: if the scheme component is defined, indicating that the reference starts with a scheme name, then the reference is interpreted as an absolute uri and we are done. otherwise, the reference uri's scheme is inherited from the base uri's scheme component. due to a
loophole in prior specifications (rfc1630), some parsers allow the scheme name to be present in a relative uri if it is the same as the base uri scheme. unfortunately, this can conflict with the correct parsing of non-hierarchical uri. for backwards compatibility, an implementation may work around such references by removing the scheme if it matches that of the base uri and the scheme is known to alwa...
Reading from Files - Archive of obsolete content
f-8 encoding, the number of characters will always be equal to or smaller than the number of bytes available. for normal file streams, the available method will return the total number of bytes left in the file to read. in effect, the above code ends up reading the entire contents of the file into a single string. the available method returns 0 if there is no more data to read, so you could use a
loop to read a number of strings. this example keeps reading 10 character strings from a file until there is no more data to read. note that the last string read may be less than ten characters long. while(stream.available()) output += stream.readstring(10); the close method is used at the end to close the stream when you are finished reading from it. you should always strive to close a stream when...
Document Object Model - Archive of obsolete content
dnodes list. in mozilla, the latter method is more efficient. the following example shows how to iterate over the children of the root node: var childnodes = document.documentelement.childnodes; for (var i = 0; i < childnodes.length; i++) { var child = childnodes[i]; // do something with child } the childnodes variable will hold the children of the document root element. we then use a for
loop to iterate over the children, accessing each item using an array-like notation. find files example so far: source view see also a re-introduction to javascript javascript reference next we'll learn how to modify the dom. « previousnext » ...
Manipulating Lists - Archive of obsolete content
the first selected item is always retrieved as the size of the array will decrease as the items are removed. next, we remove the item using the removeitemat() function. since this function requires an index we can convert between an item and an index using the getindexofitem() function. there is also a corresponding getitematindex() function to do th...
Tree Selection - Archive of obsolete content
retrieve the set of selected items or modify the selection. because the selected items in a multiple selection tree are not necessarily contiguous, you can retrieve each block of contigous selections using the getrangecount() and getrangeat() functions. the first function returns the number of selection ranges there are. if only one value is selected, this value will be 1. you would then write a
loop for the number of ranges, calling getrangeat() to get the actual indices of the start and end of the range. the getrangeat() function takes three arguments. the first is the range index. the second is an object which will be filled in by the function with the index of the first selected item. the third argument is an object which will be filled in with the index of the last selected item. ...
Using the Editor from XUL - Archive of obsolete content
e place where the text is to be inserted. now we are ready to actually insert the text. recall that we're going through a generic inserttext() call, so this code deals with pasting long strings, as well as inserting single characters. the code thus has to do the correct thing with linebreaks, so has a special case for inserting into <pre> sections. we call into the normal insertion code, which
loops through the input string looking for linebreaks, and inserts each text run, followed by a <br> when necessary. when handling key presses, this will just insert a single character. we fall out of the willdoaction() call, and drop into willdoaction(), which, for text insertion, does nothing. the last thing that happens on a keypress is that nstexteditorkeylistener::keypress() calls scrollsel...
2006-10-27 - Archive of obsolete content
for testing! - with firefox 2.0 out the door, it's time to make sure that all 1.5.0.x users are updated with the latest and greatest in stability and security fixes! testers are needed. discussions need to unit test innerhtml - someone needs to unit test innerhtml. 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. cross-domain testing - someone is suggesting that there needs to be some way of running cross-domain tests (security, web compat, etc), and is wondering if it's possible with the current test http server? update welcome page - a bug has been discovered when updating to firefox 2.0. when the special homepage comes up after updating firefox, the "go to yo...
2006-10-06 - Archive of obsolete content
okmark: protocol is defunct, apparently ben goodger disabled it back in 12/2003, shortly after he added it. webcal: & swebcal: should also be allowed as the security manager doesn't differentiate between access types. other this is for allowing protocol handlers to define a custom security model (see bug 120373). there is no consensus in the posts as to if this should be allowed. problem
looping c_opensession problem in thunderbird christian bongiorno has run into a problem developing a pkcs11 module for a new card. thunderbird is continuously repeating 7 functions including c_opensession which accesses the card that he is developing. meetings none during this week. ...
Plugins - Archive of obsolete content
any other gecko-based browser. plugins: samples and test cases npapi plugin samples and test cases. external resources for plugin creation external projects, frameworks, and blog posts that may be useful. xembed extension for mozilla plugins recent versions of mozilla on *nix-based systems include an extension for writing plugins that use xembed instead of using the old xt-based main
loop that most plugins have been using since the netscape 3.x days. categories interwiki language links join the plugin development community choose your preferred method for joining the discussion: mailing list newsgroup rss feed ...
Iterator - Archive of obsolete content
the iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. syntax iterator(object, [keyonly]) parameters object object to iterate over properties. keyonly if keyonly is truthy value, iterator.prototype.next returns property_name only. description returns iterator instance that iterates over object. ...
Generator comprehensions - Archive of obsolete content
examples simple generator comprehensions (for (i of [1, 2, 3]) i * i ); // generator function which yields 1, 4, and 9 [...(for (i of [1, 2, 3]) i * i )]; // [1, 4, 9] var abc = ['a', 'b', 'c']; (for (letters of abc) letters.tolowercase()); // generator function which y...
StopIteration - Archive of obsolete content
the stopiteration object was used to tell the end of the iteration in the legacy iterator protocol. do not use this ancient feature. syntax stopiteration description stopiteration is a part of legacy iterator protocol, and it will be removed at the same time as legacy iterator and legacy generator. examples stopiteration is thrown by iterator. ...
Reference - Archive of obsolete content
in addition to this, however, date is also a constructor function: it constructs objects of the class date, and thus is an instance of both object and function, whereas math is merely an instanceof object. --sevenspade 14:23, 17 january 2007 (pst) new javascript features, such as "for each...in" this page doesn't mention core_javascript_1.5_reference:statements:for_each...in. the for each...in
loop should either be listed on this page or moved to a different category. and somebody should see if there are other features in the same situation. herorev 00:49, 27 october 2006 (pdt) since the for each...in
loop is a 1.6 feature (not a 1.5 feature), maybe someone should rename this page/category to be either a general javascript reference or update it to be the 1.6 reference. having 1.6 features...
Implementation Status - Archive of obsolete content
mon attributes supported 3.2.2 linking attributes supported 3.2.3 single-node binding attributes supported 3.2.4 node-set binding attributes supported 3.2.5 model item property attributes partial in some cases a
loop error can occur on valid bindings 302168; 3.3.1 model supported 3.3.2 instance partial instance element with two child element does not trigger exception 337302; 3.3.3 submission partial no support for @indent and complex schema validation 278761; 278762; ...
RDF in Mozilla FAQ - Archive of obsolete content
// now see if it's loaded or not... var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } say the datasource wasn't loaded, and is loading asynchronously. using this api and javascript's settimeout(), one could set up a polling
loop that would continually check the loaded property. this is kludgy, and even worse, won't detect a failed load, for example, if there wasn't any data at the url! for this reason, there is an observer interface that allows you to spy on a datasource's progress. the following code illustrates its usage: // this is the object that will observe the rdf/xml load's progress var observer = { onbeginlo...
Square tilemaps implementation: Scrolling maps - Game development
(and therefore the rendering of the other tiles) is offset by. since the camera is pointing at (5, 10), we know that the first tile should be shifted by (-5,-10) pixels. in our demo the shifting amount is stored in the offsetx and offsety variables. var offsetx = -this.camera.x + startcol * map.tsize; var offsety = -this.camera.y + startrow * map.tsize; with these values in place, the
loop that renders the map is quite similar to the one used for rendering static tilemaps. the main difference is that we are adding the offsetx and offsety values to the target x and y coordinates, and these values are rounded, to avoid artifacts that would result from the camera pointing at positions with floating point numbers. for (var c = startcol; c <= endcol; c++) { for (var r = startro...
Tiles and tilemaps overview - Game development
world view.) side-view (like platformers such as super mario bros.) static tilemaps a tilemap can either fit into the visible screen area screen or be larger. in the first case, the tilemap is static — it doesn't need to be scrolled to be fully shown. this case is very common in arcade games like pacman, arkanoid, or sokoban. rendering static tilemaps is easy, and can be done with a nested
loop iterating over columns and rows. a high-level algorithm could be: for (var column = 0; column < map.columns; column++) { for (var row = 0; row < map.rows; row++) { var tile = map.gettile(column, row); var x = column * map.tilesize; var y = row * map.tilesize; drawtile(tile, x, y); } } you can read more about this and see an example implementation in square tilemaps implemen...
Techniques for game development - Game development
y data actively between your players. this article explains what this can do for you, and shows how to use libraries that make this easy. efficient animation for web games this article covers techniques and advice for creating efficient animation for web games, with a slant towards supporting lower end devices such as mobile phones. we touch on css transitions and css animations, and javascript
loops involving window.requestanimationframe. audio for web games audio is an important part of any game — it adds feedback and atmosphere. web-based audio is maturing fast, but there are still many browser differences to negotiate. this article provides a detailed guide to implementing audio for web games, looking at what works currently across as wide a range of platforms as possible. 2d collis...
Move the ball - Game development
sson at gamedev-canvas-workshop/lesson2.html. you already know how to draw a ball from working through the previous article, so now let's make it move. technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies. defining a drawing
loop to keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe(). delete all the javascript you currently have inside ...
Initialize the framework - Game development
ter two explicitly or use auto to let phaser decide which one to use. it usually uses webgl if available in the browser, falling back to canvas 2d if not. the id of the <canvas> to use for rendering if one already exists on the page (we've specified null because we want phaser to create its own.) the names to use for phaser's three key functions that load and start the game, and update the game
loop on every frame; we will use the same names to keep it clean. preload takes care of preloading the assets create is executed once when everything is loaded and ready update is executed on every frame. compare your code here's the full source code of the first lesson, running live in a jsfiddle: next steps now we've set up the basic html and learned a bit about phaser initia...
Win the game - Game development
if there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next s...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
function is a function containing a function (addsquares in this case): function addsquares(a,b) { function square(x) { return x * x; } return square(a) + square(b); }; //using ecmascript 2015 arrow notation const addsquares = (a,b) => { const square = x => x*x; return square(a) + square(b); }; a recursive function is a function that calls itself. see recursion. function
loop(x) { if (x >= 10) return;
loop(x + 1); }; //using ecmascript 2015 arrow notation const
loop = x => { if (x >= 10) return;
loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler. the way to identify an iife is by locating the extra left and right parenthesis at the...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
y-based preferences for a user interface. 254 localization collaborating, glossary, intro, localization, webmechanics localization (l10n) is the process of adapting a software user interface to a specific culture. 255 long task glossary, long tasks api, reference, web performance a long task is a task that takes more than 50ms to complete. 256
loop codingscripting, glossary, control flow, programming a
loop is a sequence of instructions that is continually repeated until a certain condition is met in computer programming. an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number. 257 lossless compressio...
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
a long task is a task that takes more than 50ms to complete. it is an uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different turns of the event
loop that exceeds 50 ms. see also long task api ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
each unit capable of executing code is called a thread. the main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app. because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite
loop, the entire browser will hang. this results in a frustrating, sluggish (or worse) user experience. however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another. this is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thre...
MDN Web Docs Glossary: Definitions of Web-related terms
isp itu j jank java javascript jpeg jquery json k key keyword l latency layout viewport lazy load lgpl ligature local scope local variable locale localization long task
loop lossless compression lossy compression ltr (left to right) m main axis main thread markup mathml media media (audio-visual presentation) media (css) metadata method microsoft edge microsoft internet explorer middleware mime mime t...
WAI-ARIA basics - Learn web development
o as live regions. let's look at a quick example — see aria-no-live.html (also see it running live). in this example we have a simple random quote box: <section> <h1>random quote</h1> <blockquote> <p></p> </blockquote> </section> our javascript loads a json file via xmlhttprequest containing a series of random quotes and their authors. once that is done, we start up a setinterval()
loop that loads a new random quote into the quote box every 10 seconds: let intervalid = window.setinterval(showquote, 10000); this works ok, but it is not good for accessibility — the content update is not detected by screenreaders, so their users would not know what is going on. this is a fairly trivial example, but just imagine if you were creating a complex ui with lots of constantly updating ...
Client-side form validation - Learn web development
} the big changes are in the javascript code, which needs to do much more heavy lifting. // there are fewer ways to pick a dom node with legacy browsers const form = document.getelementsbytagname('form')[0]; const email = document.getelementbyid('mail'); // the following is a trick to reach the next sibling element node in the dom // this is dangerous because you can easily build an infinite
loop. // in modern browsers, you should prefer using element.nextelementsibling let error = email; while ((error = error.nextsibling).nodetype != 1); // as per the html5 specification const emailregexp = /^[a-za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-za-z0-9-]+(?:\.[a-za-z0-9-]+)*$/; // many legacy browsers do not support the addeventlistener method. // here is a simple way to handle this; it's far from the ...
Introducing asynchronous JavaScript - Learn web development
ntrol the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. so you could have different actions to run on the response downloaded, such as processjson(), displaytext(), etc. note that not all callbacks are async — some run synchronously. an example is when we use array.prototype.foreach() to
loop through the items in an array (see it live, and the source): const gods = ['apollo', 'artemis', 'ares', 'zeus']; gods.foreach(function (eachname, index){ console.log(index + '. ' + eachname); }); in this example we
loop through an array of greek gods and print the index numbers and values to the console. the expected parameter of foreach() is a callback function, which itself takes two param...
Graceful asynchronous programming with Promises - Learn web development
r ui components all loaded, albeit in a not particularly attractive way! the code we provided here for displaying the items is fairly rudimentary but works as an explainer for now. note: if you get stuck, you can compare your version of the code to ours, to see what it is meant to look like — see it live, and see the source code. note: if you were improving this code, you might want to
loop through a list of items to display, fetching and decoding each one, and then
loop through the results inside promise.all(), running a different function to display each one depending on what the type of code was. this would make it work for any number of items, not just three. also, you could determine what the type of file is being fetched without needing an explicit type property. you could, f...
Introduction to events - Learn web development
tiles that disappear when selected. it is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. in the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 <div> elements using javascript. ...
Function return values - Learn web development
s in action recently in our random-canvas-circles.html example. our draw() function draws 100 random circles somewhere on an html <canvas>: function draw() { ctx.clearrect(0, 0, width, height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } inside each
loop iteration, three calls are made to the random() function, to generate a random value for the current circle's x-coordinate, y-coordinate, and radius, respectively. the random() function takes one parameter — a whole number — and it returns a whole random number between 0 and that number. it looks like this: function random(number) { return math.floor(math.random() * number); } this could ...
Test your skills: Events - Learn web development
his task to work in your own editor or in an online editor. events 3 in our final events-related task, you need to set an event listener on the <button>s' parent element (<div class="button-bar"> ... </div>), which when invoked by clicking any of the buttons will set the background of the button-bar to the color contained in the button's data-color attribute. we want you to solve this without
looping through all the buttons and giving each one their own event listener. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to a...
Introduction to web APIs - Learn web development
tically update the pixel data contained in an html <canvas> element to create 2d and 3d scenes. for example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the canvas api, or create a complex 3d scene with lighting and textures using webgl. such apis are often combined with apis for creating animation
loops (such as window.requestanimationframe()) and others to make constantly updating scenes like cartoons and games. audio and video apis like htmlmediaelement, the web audio api, and webrtc allow you to do really interesting things with multimedia such as creating custom ui controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing vide...
Useful string methods - Learn web development
program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automatically. so you'd have to actually write this: browsertype = browsertype.replace('moz','van'); active learning examples in this section we'll get you to try your hand at writing some string manipulation code. in each exercise below, we have an array of strings, and a
loop that processes each value in the array and displays it in a bulleted list. you don't need to understand arrays or
loops right now — these will be explained in future articles. all you need to do in each case is write the code that will output the strings in the format that we want them in. each example comes with a "reset" button, which you can use to reset the code if you make a mistake and c...
What is JavaScript? - Learn web development
example, we could annotate our last demo's javascript with comments like so: // function: creates a new paragraph and appends it to the bottom of the html body. function createparagraph() { let para = document.createelement('p'); para.textcontent = 'you clicked the button!'; document.body.appendchild(para); } /* 1. get references to all the buttons on the page in an array format. 2.
loop through all the buttons and add a click event listener to each one. when any button is pressed, the createparagraph() function will be run. */ const buttons = document.queryselectorall('button'); for (let i = 0; i < buttons.length ; i++) { buttons[i].addeventlistener('click', createparagraph); } note: in general more comments are usually better than less, but you should be careful if you...
Object-oriented JavaScript for beginners - Learn web development
bio() method — the output always includes the pronoun "he", even if your person is female, or some other preferred gender classification. and the bio only includes two interests, even if more are listed in the interests array. can you work out how to fix this in the class definition (constructor)? you can put any code you like inside a constructor (you'll probably need a few conditionals and a
loop). think about how the sentences should be structured differently depending on gender, and depending on whether the number of listed interests is 1, 2, or more than 2. note: if you get stuck, we have provided an answer inside our github repo (see it live) — try writing it yourself first though! other ways to create object instances so far we've seen two different ways to create an object in...
Test your skills: JSON - Learn web development
erinfo variable. the total number of kittens, and how many are male and female, in the kitteninfo variable. the values of these variables are then printed to the screen inside paragraphs. some hints/questions: the json data is provided as text inside the displaycatinfo() function. you'll need to parse it into json before you can get any data out of it. you'll probably want to use an outer
loop to
loop through the cats and add their names to the motherinfo variable string, and an inner
loop to
loop through all the kittens, add up the total of all/male/female kittens, and add those details to the kitteninfo variable string. the last mother cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why ...
JavaScript — Dynamic client-side scripting - Learn web development
taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements,
loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. introducing javascript objects in javascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javascript. you can even create your own objects to encapsulate related functions and variables into ef...
Routing in Ember - Learn web development
andles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the url, in case there is a desire to style it differently from inactive links. ...
Creating our first Vue component - Learn web development
with a unique id each time it is called. you can check if the unique ids are working by temporarily adding more <to-do-item></to-do-item> calls into app.vue, and then checking their rendered output with your browser's devtools. now we're ready to add multiple todoitem components to our app. in our next artcle we'll look at adding a set of todo item data to our app.vue component, which we'll then
loop through and display inside todoitem components using the v-for directive. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: ed...
Adding a new todo form: Vue events, methods, and models - Learn web development
what we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. this is what we'll cover in this article. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. ...
Understanding client-side JavaScript frameworks - Learn web development
arn about a few important concepts such as calling components inside other components, passing data to them via props and saving data state. 3. rendering a list of vue components at this point we've got a fully working component; we're now ready to add multiple todoitem components to our app. in this article we'll look at adding a set of todo item data to our app.vue component, which we'll then
loop through and display inside todoitem components using the v-for directive. 4. adding a new todo form: vue events, methods, and models we now have sample data in place and a
loop that takes each bit of data and renders it inside a todoitem in our app. what we really need next is the ability to allow our users to enter their own todo items into the app, and for that, we'll need a text <input>, an...
Mozilla’s UAAG evaluation report
3.1 toggle background images. (p1) c preferences, appearance, colors - "use my chosen colors, ignoring the colors and background image specified" 3.2 toggle audio, video, animated images. (p1) p animated images can be made still with the escape key animated images can be made still as a preference under preferences, privacy & security, images - "animated images should
loop" mozilla has no preference or command to toggle audio or video 3.3 toggle animated/blinking text. (p1) p the following line can be added to a user's prefs.js file to control blinking: user_pref("browser.blink_allowed", false); bug 89144 has been filed to expose this pref in the ui. mozilla doesn't support <marquee> by default. 3.4 toggle scripts. (p1) g ...
Adding phishing protection data providers
a provider to install a data provider for phishing protection, it's necessary to set a series of preferences to provide details about the provider. each data provider has a unique id number. the data provider with the id number 0 is the default data provider shipped with firefox. when installing a new provider, you should use the next unused number. to find an id number to use, you can build a
loop that requests the value of browser.safebrowsing.provider.0.name, then browser.safebrowsing.provider.1.name, and so forth until no value is returned. then you can use that value. you can find examples of how to read and write preferences in the article adding preferences to an extension. required preferences browser.safebrowsing.provider.idnum.name a human-readable name for the data provider...
Benchmarking
itations in the ui for inverted call stack top function analysis which is very useful for finding heavy functions that call into a whole bunch of code. currently such functions may be easy to miss looking at a profile, so feel free to also use your favorite native profiler. it also lacks features such as instruction level profiling which can be helpful in low level profiling, or finding the hot
loop inside a large function, etc. some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux. ...
Error codes returned by Mozilla APIs
0016) ns_error_ftp_pasv (0x804b0017) ns_error_ftp_pwd (0x804b0018) ns_error_not_resumable (0x804b0019) ns_error_invalid_content_encoding (0x804b001b) the content encoding of the source document was incorrect, for example returning a plain html document advertised as content-encoding: gzip ns_error_ftp_list (0x804b001c) ns_error_unknown_host (0x804b001e) ns_error_redirect_
loop (0x804b001f) ns_error_entity_changed (0x804b0020) ns_error_unknown_proxy_host (0x804b002a) ns_error_unknown_socket_type (0x804b0033) ns_error_socket_create_failed (0x804b0034) ns_error_cache_key_not_found (0x804b003d) ns_error_cache_data_is_stream (0x804b003e) ns_error_cache_data_is_not_stream (0x804b003f) ns_error_cache_wait_for_validation (0x804b0040) ns_erro...
HTMLIFrameElement.getScreenshot()
warning: removed in firefox 65. the getscreenshot() method of the htmliframeelement lets you request a screenshot of a content <iframe>, scaled to fit within a specified maximum width and height. the image will be cropped if necessary but will not be distorted vertically or horizontally. note: getscreenshot() waits for the event
loop to go idle before it takes the screenshot. it won't wait more than 2000ms (this delay is defined by the gecko dom.browserelement.maxscreenshotdelayms preference). syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); returns a domrequest for handling the screenshot request. its request.onsuccess handler handles the success case (the screenshot is contained in request.result as a blob objec...
mozbrowsererror
il the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred. ...
Embedding Tips
the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. hint, add a native message processing
loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the nsiwebbrowserprint::print() method supplying a print settings object (e.g. that returned from nsiwebbrowserprint::getglobalprintsettings) that you wish to print the page with. how do i print preview a page? query...
How to Report a Hung Firefox
s. if that's not you, or you just want to fix a firefox hang without reporting it, see firefox hangs or is not responding - how to fix. is your firefox not responding? or are you regularly seeing the "firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code error within firefox itself, such as a deadlock or infinite
loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. what information to include in a bug report as usual, following bug writing guidelines will make your report much more likely to lead to a fix in firefox. check the cpu usage of the firefox process(es): is it idle, using 100% of a core (which may show up as...
JavaScript Tips
esults.ns_nointerface; }, observe: function observe(asubject, atopic, astate) { } } when declaring xpcom methods, try to use the same names for method parameters as are used in the interface definition. dom elements dom elements are just xpcom objects with some of the interfaces precached. don't call getattribute to see if an attribute exists, call hasattribute instead. prefer to
loop through childnodes rather than using first/lastchild with next/previoussibling. but prefer haschildnodes() to childnodes.length > 0. similarly prefer document.getelementsbytagname(atag).item(0) != null to document.getelementsbytagname(atag).length > 0. prefer to use localname rather than tagname. xul elements have many of the attributes mapped to properties. this was done for a reason, so use t...
CustomizableUI.jsm
g up the position and using insertitem in the old api, but a lot less work for consumers. always prefer this over using toolbar.insertitem() (which might no-op because it delegates to addwidgettoarea) or, worse, moving items in the dom yourself. nb: why is this api per-window, you wonder? because if you need this, presumably you yourself need to create the widget in all the windows and need to
loop through them anyway, and there's no point in attempting to do this for all windows if the widget hasn't been created yet in those windows. parameters awidgetid the id of the widget that was just created awindow the window in which you want to ensure it was added. beginbatchupdate() start a batch update of items. during a batch update, the customization state is not saved to the user's p...
DeferredTask.jsm
ostponed task immediately. void flush(); cancel obsolete since gecko 28 cancel any pending task. void cancel(); arm request the execution of the task after the delay specified on construction. multiple calls don't introduce further delays. if the task is running, the delay will start when the current execution finishes. the task will always be executed on a different tick of the event
loop, even if the delay specified on construction is zero. multiple "arm" calls within the same tick of the event
loop are guaranteed to result in a single execution of the task. by design, this method doesn't provide a way for the caller to detect when the next execution terminates, or collect a result. in fact, doing that would often result in duplicate processing or logging. if a special operation...
JavaScript OS.Constants
constant, you should check that it is defined. error values eacces permission denied eagain resource temporarily unavailable ebadf bad file descriptor eexist file exists efault bad address efbig file too large einval invalid argument eio input/output error eisdir is a directory e
loop (not always available under windows) too many levels of symbolic links. emfile too many open files in the process enametoolong name too long enfile too many open files on the system enoent no such file or directory enomem cannot allocate memory enospc no space on device enotdir is not a directory ...
Task.jsm
enerator function because it contains the // "yield" operator at least once. let's create a promise object, wait on // it and capture its resolution value. let mypromise = getpromiseresolvedontimeoutwithvalue(1000, "value"); let result = yield mypromise; // this part is executed only after the promise above is resolved (after // one second, in this imaginary example). we can easily
loop while // calling asynchronous functions, and wait multiple times. for (let i = 0; i < 3; i++) { result += yield getpromiseresolvedontimeoutwithvalue(50, "!"); } return "resolution result for the task: " + result; }).then(function (result) { // result == "resolution result for the task: value!!!" // the result is undefined if no special task.result exception was thrown. }, func...
MailNews automated testing
f xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators. in the long term we would like to lose this extra complexity in favor of the event-
loop-spinning style of operation used by mozmill. message synthesis: create messages by specifying what properties the messages should have. message injection: inject synthesized messages via local or imap (using a fake server). message manipulation: mark messages as read, tag them, untag them, move them to other folders, trash them, etc. enhanced logging: supports generating rich json streams to ...
I/O Functions
a pollable event is a special kind of file descriptor. the only i/o operation you can perform on a pollable event is to poll it with the pr_poll_read flag. you cannot read from or write to a pollable event. the purpose of a pollable event is to combine event waiting with i/o waiting in a single pr_poll call. pollable events are implemented using a pipe or a pair of tcp sockets connected via the
loopback address, therefore setting and/or waiting for pollable events are expensive operating system calls. do not use pollable events for general thread synchronization; use condition variables instead. a pollable event has two states: set and unset. events are not queued, so there is no notion of an event count. a pollable event is either set or unset. pr_newpollableevent pr_destroypollableeve...
NSPR Error Handling
on a file has failed because the file is already locked. pr_file_too_big_error completing the write or seek operation would have resulted in a file larger than the system could handle. pr_no_device_space_error the device for storing the file is full. pr_pipe_error unused. pr_no_seek_device_error unused. pr_is_directory_error attempt to perform a normal file operation on a directory. pr_
loop_error symbolic link
loop. pr_name_too_long_error filename is longer than allowed by the host operating system. pr_file_not_found_error the requested file was not found. pr_not_directory_error attempt to perform directory specific operations on a normal file. pr_read_only_filesystem_error attempt to write to a read-only file system. pr_directory_not_empty_error attempt to delete a direc...
PRNetAddr
d upon. the raw member of the union is equivalent to struct sockaddr, the inet member is equivalent to struct sockaddr_in, and if the binary is built with ipv6 support, the ipv6 member is equivalent to struct sockaddr_in6. (note that prnetaddr does not have the length field that is present in struct sockaddr_in on some unix platforms.) the macros pr_af_inet, pr_af_inet6, pr_inaddr_any, pr_inaddr_
loopback are defined if prio.h is included. pr_inaddr_any and pr_inaddr_
loopback are special ipv4 addresses in host byte order, so they must be converted to network byte order before being assigned to the inet.ip field. ...
PR_Wait
of state has occurred. it is the responsibility of the programmer to evaluate the data and act accordingly. this is usually done by evaluating a boolean expression involving the monitored data. while the boolean expression is false, the thread should wait. the thread should act on the data only when the expression is true. the boolean expression must be evaluated while in the monitor and within a
loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes execution after the specified interval has expired. i...
NSS_3.12_release_notes.html
temporary files when writing them bug 251594: certificate from pkcs#12 file with colon in friendlyname not selectable for signing/encryption bug 321584: nss pkcs12 decoder fails to import bags without nicknames bug 332633: remove duplicate header files in nss/cmd/sslsample bug 335019: pk12util takes friendly name from key, not cert bug 339173: mem leak whenever secmod_handle_string_arg called in
loop bug 353904: klocwork null ptr deref in secasn1d.c bug 366390: correct misleading function names in fipstest bug 370536: memory leaks in pointer tracker code in debug builds only bug 372242: cert_comparerdn uses incorrect algorithm bug 379753: s/mime should support aes bug 381375: ocspclnt doesn't work on windows bug 398693: der_asciitotime produces incorrect output for dates 1950-1970 bug 420212:...
NSS 3.36.8 release notes
vailable on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_8_rtm/src/ other releases are available in nss releases. new in nss 3.36.8 new functionality no new functionality is introduced in this release. this is a patch release to fix bugs. bugs fixed in nss 3.36.8 1554336 - optimize away unneeded
loop in mpi.c 1515342 - more thorough input checking (cve-2019-11729) 1540541 - don't unnecessarily strip leading 0's from key material during pkcs11 import (cve-2019-11719) compatibility nss 3.36.8 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.36.8 shared libraries without re...
NSS 3.44.1 release notes
.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_1_rtm/src/ other releases are available in nss releases. ...
NSS 3.45 release notes
1 modules if c_getslotinfo() returns error bug 1551041 - fix builds using gcc < 4.3 on big-endian architectures bug 1554659 - add versioning to openbsd builds to fix link time errors using nss bug 1553443 - send session ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded
loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequestcallback return code for rejecting 0-rtt bug 1556591 - eliminate races in uses of pk11_setwrapkey bug 1558681 - stop using a global for anti-replay of tls 1.3 early data bug 1561510 - fix...
NSS sources building testing
e which hostname to use. as a test, it must be possible to successfully use the command "ping $host.$domsuf" on your computer (ping reports receiving replies). on many computers the variables host=localhost domsuf=localdomain works. in case you built nss in 64 bits, you need to set the use_64 environment variable to 1 to run the tests. if you get name resolution errors, try to disable ipv6 on the
loopback device. after you have set the required environment variables, use "cd nss/tests" and start the tests using "./all.sh". the tests will take a while to complete; on a slow computer it could take a couple of hours. once the test suite has completed, a summary will be printed that shows the number of failures. you can find the test suite results in directory nss/../tests_results (i.e. the resu...
nss tech note4
there is a long list of pre-defined oids, and new ones can be added dynamically by an application. the oid data structure contains an array of identifier bytes (each byte is a "level" in a hierarchical namespace), a text description, and some other things. ...
NSS PKCS11 Functions
ttempts to enter a password and do not allow further attempts after a certain point. therefore, if the retry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless
loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, mozilla uses the parameter to pass information about which window is associated with the modal dialog box req...
Python binding for NSS
n data or the der_is_signed flag so this change should be backwards compatible. fix bug #922247, pkcs12decoder.database_import() method. importing into a nss database would sometimes fail or segfault. error codes and descriptions were updated from upstream nspr & nss. the password callback did not allow for breaking out of a password prompting
loop, now if none is returned from the password callback the password prompting is terminated. nss.nss_shutdown_context now called from initcontext destructor, this assures the context is shutdown even if the programmer forgot to. it's still best to explicitly shut it down, this is just failsafe. support was added for shutdown callbacks. cert_dump.
pkfnc.html
ttempts to enter a password and do not allow further attempts after a certain point. therefore, if the retry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless
loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, communicator uses the parameter to pass information about which window is associated with the modal dialog b...
NSS_3.12.3_release_notes.html
oken's c_initialize and c_finalize should succeed after a fork in a child process bug 473944: trust anchor is not trusted when requirefreshinfo flag is set. bug 474532: softoken cannot import certs with empty subjects and non-empty nicknames bug 474777: wrong deallocation when modifying crl. bug 476126: cert_asciitoname fails when avas in an rdn are separated by '+' bug 477186: infinite
loop in cert_getcertchainfromcert bug 477777: selfserv crashed in client/server tests. bug 478171: consolidate the coreconf/xxx.mk files for windows bug 478563: add _msc_ver (the cl version) to coreconf. bug 478724: nss build fails on windows since 20090213.1 nightly build. bug 478931: object leak in pkix_list_mergelists function bug 478994: allow softoken's fork check to be disabled bug...
Multithreading in Necko
tially on the background threads to improve performance. for example, the http protocol handler has code that runs on the socket transport thread to kick off pending requests well before the main thread would get around to doing so. socket transport thread (1) socket connections are processed on a single background thread. this thread is controlled by the nssockettransportservice. it sits in a
loop, polling a list of sockets. when a socket can be read, the socket's listener is notified either synchronously (on the same thread) or asynchronously via a nsistreamlistenerproxy impl. file transport threads (1-4) file i/o is processed via a thread pool that has between 1 and 4 threads. these threads are controlled by the nsfiletransportservice. each file transport object is given time on one o...
Performance Hints
ction sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; return result; } this is not equivalent code because the second version does not modify global variables result and i. however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a
loop like the one in sum!). arrays use the forms of the array constructor that specify a size or take a list of initial elements. for example, the code var a = new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new array(n). a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of...
Hacking Tips
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). or if this is an intermittent, run it in a
loop capturing an rr log for every one until it fails: n=1; while rr ...same.as.above...; do echo passed $n; n=$(( $n + 1 )); done wait until it hits a failure. now you can run rr replay to replay that last (failed) run under gdb. rr with reftest to break on the write of a differing pixel: find the x/y of a pixel that differs use 'run z' where z is the mark in the log for test-start. for examp...
Exact Stack Rooting
rooting should have similar performance. the performance tradeoffs that these techniques make, however, are quite different. if the extra overhead of exact rooting does end up adding an unacceptable cost to a specific code path that is not mitigated by a faster gc, there are some tricks you can use to get better performance at the cost of more complex code. move js::rootedt declarations above
loops. modern c++ compilers are not smart enough to do licm on js::rootedt, so forward declaring a single js::rootedt above the
loop and re-using it on every iteration can save some cycles. raw pointers. if you are 100% sure that there is no way for spidermonkey to gc while the pointer is on the stack, this is an option. note: spidermonkey can gc because of any error, gc because of timers, gc because...
Introduction to the JavaScript shell
this article explains how to use the shell to experiment with javascript code and run javascript programs. to get the spidermonkey javascript shell, see the spidermonkey build documentation or download a compiled binary for your platform from the nightly builds. for a list of other javascript shells, see javascript shells. ...
JIT Optimization Strategies
hat has not changed after it was first assigned, is likely a constant property. it then directly inlines the value of the property into hot code that accesses it. for example, in the following code: var constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) return true; } return false; } will have the
loop compiled into the following when testarray gets hot. for (var i = 0; i < array.length; i++) { if (array[i] > 100) return true; } when this optimization is successful, property access is eliminated entirely and replaced with an inline constant. getprop_constant attempts to optimize reading a property that contains a uniquely-typed (or "singleton") object. with uniquely-typed objects, it...
JSAPI Cookbook
hich gives javascript code fine-grained control over the behavior of individual properties of any object. you can use this function to create a constant property, one that can't be overwritten or deleted. specify writable: false to make the property read-only and configurable: false to prevent it from being deleted or redefined. the flag enumerable: true causes this property to be seen by for-in
loops. // javascript object.defineproperty(obj, "prop", {value: 123, writable: false, enumerable: true, configurable: false}); the analogous jsapi function is js_defineproperty. the property attribute jsprop_readonly corresponds to writeable: false, jsprop_enumerate to enumerable: true, and j...
JSAPI User Guide
o make "one-off" objects. */ jsclass my_class = { "myclass", /* all of these can be replaced with the corresponding js_*stub function pointers. */ my_addproperty, my_delproperty, my_getproperty, my_setproperty, my_enumerate, my_resolve, my_convert, my_finalize }; jsobject *obj; /* * define an object named in the global scope that can be enumerated by * for/in
loops. the parent object is passed as the second argument, as * with all other api calls that take an object/name pair. the prototype * passed in is null, so the default object prototype will be used. */ obj = js_defineobject(cx, globalobj, "myobject", &my_class, nullptr, jsprop_enumerate); /* * define a bunch of properties with a jspropertyspec array statically * initial...
JSClass.flags
jsclass_emulates_undefined added in spidermonkey 24 causes objects which have this class to emulate undefined in certain circumstances. an object obj that emulates undefined behaves like any other object, except in the following ways: typeof obj === "undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions,
loop continuation/termination conditions [for/while/do { } while], the condition in a ternary ?: expression, and so on) (obj == undefined) is true, and (obj != undefined) is false (obj == null) is true, and (obj != null) is false == and != comparisons to values other than null or undefined (including to an object that emulates undefined) are unaffected by this flag. strict equalit...
JSConstDoubleSpec
added in spidermonkey 38 name type description val double or int32_t value for the double or integer. name const char * name to assign the double. flags uint8_t property attributes for the double. obsolete since jsapi 35 currently these can be 0 or more of the following values or'd: jsprop_enumerate: property is visible in for
loops. jsprop_readonly: property is read-only. jsprop_permanent: property cannot be deleted. jsprop_exported: property can be exported outside its object. jsprop_index: property is actually an array element. if this field is 0, js_defineconstdoubles uses the default attributes jsprop_readonly | jsprop_permanent instead. spare uint8_t [3] reserved for fut...
JSNewEnumerateOp
38, jsnewenumerateop is the type of objectops::enumerate. this callback overrides a portion of spidermonkey's default [[enumerate]] internal method. when an ordinary object is enumerated, that object and each object on its prototype chain is tested for an enumerate op, and those ops are called in order. the properties each op adds to the properties vector are added to the set of values the for-in
loop will iterate over. all of this is nonstandard. an object is "enumerated" when it's the target of a for-in
loop or js_enumerate. all other property inspection, including object.keys(obj), goes through [[ownkeys]]. the callback's job is to populate properties with all property keys that the for-in
loop should visit. before jsapi 37, jsnewenumerateop was the type of jsclass.enumerate. to use a ...
JSPropertyDescriptor
to be called when there is an attempt to set that property. value describes the value of the specified property, which can be any valid javascript value (function, object, string...) configurable declare that the property can be modified and deleted enumerable declare that the property can be enumerated, and the enumerable genus can be traversed by the for...in
loop. writable declare whether the specified attribute can be rewritten description a descriptor is a property that describes an object's properties. there are two main types of property descriptors that exist in an object: a data descriptor and an access descriptor. you can use the object.getownpropertydescriptor() function to get the corresponding property of an object. descripto...
JS_EnumerateStandardClasses
executable script context for which to initialize js function and object classes. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject an object to enumerate standard classes. description the global object's class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in
loops any classes not yet resolved lazily. see also mxr id search for js_enumeratestandardclasses js_resolvestandardclass ...
JS_NewPropertyIterator
text * the js context in which to enumerate properties. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle<jsobject*> the object whose properties are to be enumerated. description create an object to iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in
loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this returns an iterator object that can be passed to js_nextproperty to fetch the property ids. on error, it returns null. the iterator object created by this function is not a javascript iterator. it is an opaque ob...
JS_ResolveStandardClass
a top-level property induced by initializing a standard class, store false in *resolved and just return true. return false on error, as usual for bool result-typed api entry points. this api can be called directly from a global object class's resolve op, to define standard classes lazily. the class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in
loops any classes not yet resolved lazily. see also mxr id search for js_resolvestandardclass js_enumeratestandardclasses ...
JS_SetOptions
nkey 15 ecmascript for xml (e4x) support: parse <!-- --> as a token, not backward compatible with the comment-hiding hack used in html script tags. only used if jsoption_allow_xml is set. mxr id search for jsoption_moar_xml jsoption_native_branch_callback the branch callback set by js_setbranchcallback may be called with a null script parameter, by native code that
loops intensively. mxr id search for jsoption_native_branch_callback jsoption_dont_report_uncaught when returning from the outermost api call, prevent uncaught exceptions from being converted to error reports. mxr id search for jsoption_dont_report_uncaught jsoption_relimit added in spidermonkey 1.8 throw an exception if a regular exp...
JS_SetPropertyAttributes
description js_setpropertyattributes sets the attributes for a specified property, name of an object obj. js_setucpropertyattributes is the unicode version of the function. attrs is an unsigned integer containing the attribute value to set. it is the bitwise or of zero or more of the following values: flag purpose jsprop_enumerate property is visible in for and in
loops. jsprop_readonly property is read only. jsprop_permanent property cannot be deleted. jsprop_exported property can be imported by other objects. jsprop_index property is actually an index into an array of properties, and is cast to a const char *. if js_setpropertyattributes cannot locate an object with the specified property, it returns js_f...
JS_SetPrototype
to get an object's prototype, use js_getprototype. see also lxr id search js_getprototype ...
JS_ThrowStopIteration
ed in spidermonkey js1.8 throw a stopiteration exception. syntax bool js_throwstopiteration(jscontext *cx); name type description cx jscontext * the context in which to throw the stopiteration object. description js_throwstopiteration throws the appropriate stopiteration object for the function currently executing in cx. in for…in and for each…in
loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators. the .next method may throw stopiteration when there are no more values left to iterate. the engine automatically catches the exception and exits the
loop. jsclass.enumerate offers a simpler way to customize object iteration. see also mxr id search for ...
Property attributes
property attributes. the jsapi expresses property attributes as a value of type unsigned, the bitwise or of zero or more of the jsprop flags described below. an application can set property attributes when creating a property. see js_defineproperty, js_fs, and js_fn flag description jsprop_enumerate the property is visible to javascript for...in and for each ... in
loops, as well as to js_enumerate. this is the inverse of the ecma standard dontenum attribute. mxr id search for jsprop_enumerate jsprop_readonly the property's value cannot be set. in javascript 1.2 and lower, it is an error to attempt to assign a value to a read-only property. in javascript 1.3 and higher, as in ecmascript, attempts to set a value on a read-only prope...
Shell global objects
scripted function or has not been compiled by ion, null is returned. dumpscopechain(obj) prints the scope chain of an interpreted function or a module. crash([message]) crashes the process with a moz_crash. setarmhwcapflags("flag1,flag2 flag3") on non-arm, no-op. on arm, set the hardware capabilities. the list of flags is available by calling this function with help as the flag's name wasm
loop(filename, imports) performs an afl-style persistent
loop reading data from the given file and passing it to thewasmeval function together with the specified imports object. testing functions testing functions are available also on firefox via components.utils.getjstestingfunctions() functions always available gc([obj] | 'zone' [, 'shrinking']) run the garbage collector. when obj is given...
Animated PNG graphics
control chunk the 'actl' chunk is an ancillary chunk as defined in the png specification. it must appear before the first 'idat' chunk within a valid png stream. the 'actl' chunk contains: byte offset field name field type description 0 num_frames unsigned int the number of frames in the apng. 4 num_plays unsigned int the number of times to
loop this apng. 0 indicates infinite
looping. num_frames indicates the total number of frames in the animation. this must equal the number of 'fctl' chunks. 0 is not a valid value. 1 is a valid value for a single-frame apng. if this value does not equal the actual number of frames it should be treated as an error. num_plays indicates the number of times that this animation should play; if it i...
Finishing the Component
turning true. if these two strings do not match, then the component returns return false and blocks the load. uri caching caching the uri would make this method implementation much faster by avoiding the need to create and destroy so many objects. this points out an important drawback of xpcom, which is that you cannot create an object on the stack. creating this many objects is ok in a tight
loop if the buffer of memory that holds the contents of the urls is guaranteed to be valid for the lifetime of the object. but regardless of how optimized the implementation is with respect to is memory usage, a heap allocation will be made for every xpcom object created. the string comparison with the url type "http", "https", and "ftp" looks like this: nsembedcstring scheme; contentlocation->gets...
Starting WebLock
remaining elements in the enumerator. * pr_false if there are no more elements in the enumerator. */ boolean hasmoreelements(); /** * called to retrieve the next element in the enumerator. the "next" * element is the first element upon the first call. must be * preceded by a call to hasmoreelements() which returns pr_true. * this method is generally called within a
loop to iterate over * the elements in the enumerator. * * @see hasmoreelements() * @return ns_ok if the call succeeded in returning a non-null * value through the out parameter. * ns_error_failure if there are no more elements * to enumerate. * @return the next element in the enumeration. */ nsisupports getnext(); }; implem...
Mozilla internal string guide
ar16_t(' '); } } you may change the length of a string via setlength(). note that iterators become invalid after changing the length of a string: /** * replace every tab character in `data` with four spaces. */ void replacetabs2(nsastring& data) { int len = data.length(); char16_t *cur = data.beginwriting(); char16_t *end = data.endwriting(); // because `cur` may change during the
loop, track the position // within the string. int pos = 0; while (cur < end) { if (char16_t('\t') != *cur) { ++pos; ++cur; } else { len += 3; data.setlength(len); // after setlength, read `cur` and `end` again cur = data.beginwriting() + pos; end = data.endwriting(); // move the remaining data over if (pos < len - 1) memmo...
Interfacing with the XPCOM cycle collector
ans that every edge involved in a cycle must be participating, otherwise the cycle will not be found. the traverse and unlink methods on the helper object are not magic; they are programmer-supplied and must be correct, or else the collector will fail. the collector does not know how to find temporary owning pointers that exist on the stack, so it is important that it only run from near the top-
loop of the program. it will not crash if there are extra owning pointers, but it will find itself unable to account for the reference counts it finds in the owned objects, so may fail to collect cycles. how to make your classes participate the interface between the cycle collector and your classes can be accessed directly using the contents of xpcom/base/nscyclecollector.h, but there are convenien...
Components.classes
ered on the machine then trying to access it will generate a javascript warning in strict mode and the value returned will be the javascript value undefined. you should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in components.classes)) // do something... the properties of the components.classes object can be enumerated using a for...in
loop. usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or t...
Components.interfaces
javascript. properties of the components.interfaces object are used where xpcom methods expect a parameter of type nsid. this includes nsisupports.queryinterface(), the optional parameter accepted by nsijscid.getservice(), nsijscid.createinstance() when called from javascript, and nsiclassinfo.getinterfaces(). the properties of the components.interfaces object can be enumerated using a for...in
loop. usage accessing an interface object properties of the components.interfaces object are indexed by interface name. you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will return you the interface object for the nsisupportsarray interface. accessing constants defined in an interface interface descriptions (cf. xpidl) may not only contain me...
Components.results
the names of well-known xpcom result codes, with each value being that of the corresponding result code. elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw components.results.ns_error_unexpected; the elements of the components.results object can be enumerated using a for-in
loop. usage implementing nsisupports the standard nsisupports is usually implemented in javascript by using components.results to get a failure return value if does not implement the given interface. note the common use of an abbreviation for components.results, cr: const ci = components.interfaces, cr = components.results; function class() { /* ... */ } class.prototype = { /* ... */ queryi...
Observer Notifications
alled to shut down the quotamanager; this is separated from profile-before-change to allow everything inside profile-before-change to continue using it. profile-before-change-telemetry called to shut down telemetry, again separated to allow everything before this event to continue using it. xpcom-will-shutdown called just before xpcom-shutdown. observer must not spin event
loop. xpcom-shutdown assortment of critical services stop operating. many things will not be available here. web-workers-shutdown called inside xpcom-shutdown. this shuts down all web workers. xpcom-shutdown-threads shuts down the thread manager, causing all nsthreads to finish processing any events already queued and stop accepting new events. browser these...
IAccessible2
ject for use when it would be helpful to access the window handle in cases where an event isn't fired on this object. a use case is when a screen reader is grabbing an entire web page on a page load. without the availability of windowhandle, the at would have to get the window handle by using windowfromaccessibleobject on each iaccessible, which is slow because it's implemented by oleacc.dll as a
loop which crawls up the ancestor chain and looks for a role_window object, mapping that back to a window handle. [propget] hresult windowhandle( [out] hwnd windowhandle ); parameters windowhandle return value s_ok. remarks when you have a reference to an iaccessible and require a reference to an iaccessible2 use queryservice as follows: // pacc is a reference to the accessible object's iaccessi...
nsIDocShell
the new history entry. for instance, if the user tries to reload the page, then this is the url that will be reloaded. areplace whether to modify the current history entry instead of creating a new one. beginrestore() begin firing webprogresslistener notifications for restoring a page presentation. this method will post an event to complete the simulated load after returning to the event
loop. void beginrestore( in nsicontentviewer viewer, in boolean top ); parameters viewer the content viewer whose document we are starting to load. if null, it defaults to the docshell's current content viewer, creating one if necessary. top should be true for the toplevel docshell that is being restored; it will be set to false when this method is called for child docshells. cr...
nsIFaviconService
ecify the mime type unless you're clearing the data. you can set the data even if you haven't called setfaviconurlforpage() yet. it will be stored but will not be associated with any page. however, any favicons not associated with a visited web page, bookmark, or "place:" uri will be expired when history cleanup is done. this might be done at any time on a timer, so you should not let the message
loop run between calls or your icon may get deleted. it is best to set the favicon data, and then associate it with a page. this will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. the expiration time is stored. this will be used if you call setandloadfaviconforpage() to see whether the data needs reloading. do not use this ...
nsIHttpChannel
t pipelining. this attribute may only be set before the channel is opened. exceptions thrown ns_error_failure if set after the channel has been opened. redirectionlimit unsigned long this attribute specifies the number of redirects this channel is allowed to make. if zero, the channel will fail to redirect and will generate a ns_error_redirect_
loop failure status. note: an http redirect results in a new channel being created. if the new channel supports nsihttpchannel, then it will be assigned a value to its redirectionlimit attribute one less than the value of the redirected channel's redirectionlimit attribute. the initial value for this attribute may be a configurable preference (depending on the implementation). ...
nsISimpleEnumerator
ments sequentially. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsisupports getnext(); boolean hasmoreelements(); methods getnext() called to retrieve the next element in the enumerator. the "next" element is the first element upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a
loop to iterate over the elements in the enumerator. nsisupports getnext(); parameters none. return value ns_ok if the call succeeded in returning a non-null value through the out parameter. ns_error_failure if there are no more elements to enumerate. hasmoreelements() called to determine whether or not the enumerator has any elements that can be returned via getnext(). this method is generally used ...
nsIStringEnumerator
ease add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview astring getnext(); boolean hasmore(); methods getnext() called to retrieve the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a
loop to iterate over the strings in the enumerator. astring getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() called to determine whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enum...
nsIUTF8StringEnumerator
ate over a set of strings provided by the object. inherits from: nsisupports last changed in gecko 1.7 method overview autf8string getnext(); boolean hasmore(); methods getnext() returns the next string in the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmore(), which returns pr_true. this method is generally called within a
loop to iterate over the strings in the enumerator. autf8string getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, ...
nsIWebContentHandlerRegistrar
var tabs = adomwindow.gbrowser.tabcontainer.childnodes; for (var i = 0; i < tabs.length; i++) { console.log(tabs[i].linkedbrowser.contentwindow.location); if (tabs[i].linkedbrowser.contentwindow.location.hostname == myurihostname) { htmlcontentwindow = tabs[i].linkedbrowser.contentwindow; break; //break for
loop } } if (htmlcontentwindow) { break; //break while
loop } } else { //adomwindow doest have any tabs if (adomwindow.gbrowser.contentwindow.location.hostname == myurihostname) { htmlcontentwindow = adomwindow.contentwindow; break; } } } else { ...
nsIXULWindow
m corresponding to the given id, if any. removechildwindow() tell this window that it has lost a child xul window. note that xul windows do not currently track child xul windows. void removechildwindow( in nsixulwindow achild ); parameters achild the child window being removed. showmodal() shows the window as a modal window. that is, ensures that it is visible and runs a local event
loop, exiting only once the window has been closed. void showmodal(); parameters none. ...
Frequently Asked Questions
r', must have already addrefed that pointer. if it didn't, you should probably report it as a bug. no matter which code pattern you use to solve this problem, you should comment it, e.g., // warning: this getter doesn't addref() its result. if the getter returns the new pointer as its function result, no worries, general does nscomptr bloat the code? are nscomptrs fast? can i use them in tight
loops? bibliography web resources nscomptr.h, and nscomptr.cpp are the source to nscomptr. you can examine the source to nscomptr online using (the wonderful) lxr. exploring this code is not an adventure for the faint of heart. some com ownership guidelines. interface pointers considered harmful by don box originally appeared in the september 1995 issue of "the c++ report". com smart pointers ...
Reference Manual
example. prefer destruction to assignment prefer do_queryinterface to calling queryinterface iterating there is a very common idiom for iterating over data-structures with normal pointers, e.g., // iterating with pointers to non-xpcom objects... node* p = ...; while ( p ) { // ... p = p->next; } one often sees this pattern expressed as a for
loop, as well. consider, however, what would happen if you were trying to do this with a raw xpcom interface pointer. // iterating with raw xpcom interface pointers... nsidomnode* p = ...; while ( p ) { // ... p->getnext(&p); // trouble! we overwrote |p| without |release|ing it. } oops! we just failed to release p before putting a new point...
The libmime module
...etc... } method definitions next come the definitions of the methods we referred to in the class-init function. the way to access earlier methods (methods defined on the superclass) is to simply extract them from the superclass's object. but note that you cannot get at methods by indirecting through object->class->superclass: that will only work to one level, and will go into a
loop if some subclass tries to continue on this method. the easiest way to do this is to make use of the mime_superclass macro that was defined at the top of the file, as shown below. the alternative to that involves typing the literal name of the direct superclass of the class defined in this file, which will be a maintenance headache if the class hierarchy changes. if you use the mime_superclass ...
Using COM from js-ctypes
urn 0; } converting c code to js-ctypes code now we have working c code. it could be converted into js-ctypes in almost straightforward way. clsid and iid needs clsid and iid of spvoice and ispvoice description here. com types and functions needs com types (guid) and functions (coinitialize etc) description here. converted js-ctypes code here's converted code. this example uses busy
loop and thus firefox won't respond until the speaking is done. if this code were used in a production add-on, then to avoid firefox locking up, run this code from a chromeworker. let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); // some groundwork let is64bit; if (ctypes.voidptr_t.size == 4 /* 32-bit */) { is64bit = false; } else if (ctypes.voidptr_t.size == 8 ...
Using Objective-C from js-ctypes
n call can be converted into the following js-ctypes code: let text = objc_msgsend(tmp2, initwithcstring_encoding, ctypes.char.array()("hello, firefox!"), ctypes.unsigned_long(nsutf8stringencoding)); converted js-ctypes code finally, we have our converted code. this can run with a copy-and-paste into a javascript shell. this example uses a busy
loop, and thus, firefox won't respond until the speaking is done. if this code were to be used in a production add-on, then to avoid firefox locking up, run this code from a chromeworker. let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let id = ctypes.structtype("objc_object").ptr; let sel = ctypes.structtype("objc_selector").ptr; let bool = ctypes.signed_char; le...
CData
: datacasted:', datacasted, uneval(datacasted), datacasted.tostring()); var charcode = []; var fromcharcode = [] for (var i=0; i<ptrasarr.length; i++) { //if known_len is correct, then will not hit null terminator so like in example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" if you pass length of 77, then null term will not get hit by this
loop as null term is at pos 77 and we go till `< known_len` var thisunsignedcharcode = ptrasarr.addressofelement(i).contents; if (thisunsignedcharcode == 0) { // reached null terminator, break console.log('reached null terminator, at pos: ', i); break; } charcode.push(thisunsignedcharcode); from...
Mozilla
disconnect failures. an example of such a failure how to report a hung firefox is your firefox not responding? or are you regularly seeing the "firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code error within firefox itself, such as a deadlock or infinite
loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. http cache httpd.js ime handling guide this document explains how gecko handles ime. implementing download resuming this document describes how an embedder or o...
Set a conditional breakpoint - Firefox Developer Tools
the debugger pauses. a conditional breakpoint also has a condition associated with it, which is represented as an expression. when the program reaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. this makes it possible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or errors that occur the last time through a
loop, for example. to set a conditional breakpoint, activate the context menu in the source pane, on the line where you want the breakpoint, and select "add conditional breakpoint". you'll then see a textbox where you can enter the expression. press return to finish. conditional breakpoints are shown as orange arrows laid over the line number. if you context-click on any breakpoint, you'll see a ...
Debugger.Script - Firefox Developer Tools
[] for (i=1; i < 10; i++) // it's hip to be square. a[i] = i*i; calling getalloffsets() on that code might yield an array like this: [[0], [5, 20], , [10]] this array indicates that: the first line’s code starts at offset 0 in the script; the for statement head has two entry points at offsets 5 and 20 (for the initialization, which is performed only once, and the
loop test, which is performed at the start of each iteration); the third line has no code; and the fourth line begins at offset 10. if the instance refers to webassembly code, throw a typeerror. getallcolumnoffsets(): if the instance refers to a jsscript, return an array describing the relationship between bytecode instruction offsets and source code positions in this sc...
Waterfall - Firefox Developer Tools
ay a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mark an instant in the recording. to make a timestamp marker, call console.timestamp(). you can pass an argument to label the timestamp. ...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
nstances of the range of elements. note: when using webgl2, this method is available as gl.drawarraysinstanced() by default. syntax void ext.drawarraysinstancedangle(mode, first, count, primcount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. prim...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
s of a set of elements. note: when using webgl2, this method is available as gl.drawelementsinstanced() by default. syntax void ext.drawelementsinstancedangle(mode, count, type, offset, primcount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. po...
AnimationEffect.getComputedTiming() - Web APIs
he current time of the animation in milliseconds. if the keyframeeffect is not associated with an animation, its value is null. progress indicates how far along the animation is through its current iteration with values between 0 and 1. returns null if the animation is not running or its keyframeeffect isn't associated with an animation. currentiteration the number of times this animation has
looped, starting from 0. returns null if the animation is not running or its keyframeeffect isn't associated with an animation. specifications specification status comment web animationsthe definition of 'animationeffect.getcomputedtiming()' in that specification. working draft editor's draft. ...
AudioBufferSourceNode.playbackRate - Web APIs
(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.
loop = true; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); playbackcontrol.removeattribute('disabled'); } stop.onclick = function() { source.stop(0); play.removeattribute...
AudioBufferSourceNode.start() - Web APIs
in the same time coordinate system as the audiocontext, to the time within the audio buffer that playback should begin. for example, to start playback halfway through a 10-second audio clip, offset should be 5. the default value, 0, will begin playback at the beginning of the audio buffer, and offsets past the end of the audio which will be played (based on the audio buffer's duration and/or the
loopend property) are silently clamped to the maximum value allowed. the computation of the offset into the sound is performed using the sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5. duration optional the duration of the sound to be played, specified i...
AudioContext.getOutputTimestamp() - Web APIs
system of the currenttime for the baseaudiocontext; the time after the audio context was first created. performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe
loop running, which constantly outputs the contexttime and performancetime. you can see full code of this example at output-timestamp (see it live also). play.addeventlistener('click', () => { if(!audioctx) { audioctx = new window.audiocontext(); } getdata(); source.start(0); play.setattribute('disabled', 'disabled'); raf = requestanimationframe(outputtimestamps); }); stop.addeven...
AudioNode.connect() - Web APIs
turn undefined. if the destination is an audioparam, connect() returns undefined. exceptions indexsizeerror the value specified as outputindex or inputindex doesn't correspond to an existing input or output. invalidaccesserror the destination node is not part of the same audio context as the source node. notsupportederror the specified connection would create a cycle (in which the audio
loops back through the same nodes repeatedly) and there are no delaynodes in the cycle to prevent the resulting waveform from getting stuck constructing the same audio frame indefinitely. examples connecting to an audio input the most obvious use of the connect() method is to direct the audio output from one node into the audio input of another node for further processing. for example, you might s...
AudioScheduledSourceNode.onended - Web APIs
the onended event handler for the audioscheduledsourcenode interface specifies an eventhandler to be executed when the ended event occurs on the node. this event is sent to the node when the concrete interface (such as audiobuffersourcenode, oscillatornode, or constantsourcenode) determines that it has stopped playing. the ended event is only sent to a node configured to
loop automatically when the node is stopped using its stop() method. this is the case, for example, when using an audiobuffersourcenode with its
loop property set to true. syntax audioscheduledsourcenode.onended = eventhandler; value a function which is called by the browser when the ended event occurs on the audioscheduledsourcenode. the function receives as input a single parameter, which is an object of type event ...
BaseAudioContext - Web APIs
dividual channels of an audio stream and process them separately. baseaudiocontext.createconvolver() creates a convolvernode, which can be used to apply convolution effects to your audio graph, for example a reverberation effect. baseaudiocontext.createdelay() creates a delaynode, which is used to delay the incoming audio signal by a certain amount. this node is also useful to create feedback
loops in a web audio api graph. baseaudiocontext.createdynamicscompressor() creates a dynamicscompressornode, which can be used to apply acoustic compression to an audio signal. baseaudiocontext.creategain() creates a gainnode, which can be used to control the overall volume of the audio graph. baseaudiocontext.createiirfilter() creates an iirfilternode, which represents a second order filter co...
Beacon API - Web APIs
of poor page load performance. there are other techniques used to ensure that data is submitted. one such technique is to delay the unload to submit data by creating an image element and setting its src attribute within the unload handler. as most user agents will delay the unload to complete the pending image load, data can be submitted during the unload. another technique is to create a no-op
loop for several seconds within the unload handler to delay the unload and submit data to a server. not only do these techniques represent poor coding patterns, some of them are unreliable and result in the perception of poor page load performance for the next navigation. the beacon api provides a standard way to address these issues. global context the beacon api's navigator.sendbeacon() method is...
Body.text() - Web APIs
resolves with a usvstring object (text). the response is always decoded using utf-8. syntax response.text().then(function (text) { // do something with the text response }); parameters none. return value a promise that resolves with a usvstring. example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we
loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file. when the fetch is successful, we read a usvstring (text) object ou...
CSSStyleDeclaration.setProperty() - Web APIs
amples in this example we have three buttons, which can be pressed to dynamically alter our box paragraph's border, background color, and text color to random values (see the live example at the end of this section). we know that the rule we want to alter to do this is contained inside the second stylesheet applied to the page, so we grab a reference to it using document.stylesheets[1]. we then
loop through the different rules contained inside the stylesheet, which are contained in the array found at stylesheet.cssrules; for each one, we check whether its cssstylerule.selectortext property is equal to the selector .box p, which indicates it is the one we want. if so, we store a reference to this cssstylerule object in a variable. we then use three functions to generate random values for the...
CSSUnparsedValue.entries() - Web APIs
syntax cssunparsedvalue.entries(obj) parameters obj the cssunparsedvalue whose enumerable own property [key, value] pairs are to be returned. return value an array of the given cssunparsedvalue object's own enumerable property [key, value] pairs. ...
CSSUnparsedValue - Web APIs
ted using cssvariablereferencevalue. constructor cssunparsedvalue.cssunparsedvalue() creates a new cssunparsedvalue object. properties cssunparsedvalue.length returns the number of items in the cssunparsedvalue object. methods cssunparsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object. cssunparsedvalue.keys() returns a new array iterator object that contains the keys for each index in the cssunparsedvalue object. cssunparsedvalue.values() returns a new array iterator ob...
CSS Typed Object Model API - Web APIs
perties. it consists of a list of string fragments and variable references. cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties. cssunparsedvalue.entries() method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well). cssunparsedvalue.foreach() method executing a provided function once for each element of the cssunparsedvalue. cssunparsedvalue.keys() method returning a new array iterator object that contains the keys for each index in the array. csskeywordvalue serialization the csskeywordvalue interface of t...
CanvasRenderingContext2D.arcTo() - Web APIs
= 0; i < points.length; i++) { var p = points[i]; labelpoint(p, { x: 0, y: -20 } , i) } } // draw arc const drawarc = function ([p0, p1, p2], r) { ctx.beginpath(); ctx.moveto(p0.x, p0.y); ctx.arcto(p1.x, p1.y, p2.x, p2.y, r); ctx.lineto(p2.x, p2.y); ctx.stroke(); } let t0 = 0; let rr = 0; // the radius that changes over time let a = 0; // angle let pi2 = math.pi * 2; const
loop = function (t) { t0 = t / 1000; a = t0 % pi2; rr = math.abs(math.cos(a) * r); ctx.clearrect(0, 0, canvas.width, canvas.height); drawarc([p1, p2, p3], rr); drawpoints([p1, p2, p3]); requestanimationframe(
loop); }
loop(0); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.arcto' in that s...
CanvasRenderingContext2D.createImageData() - Web APIs
vas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 50); console.log(imagedata); // imagedata { width: 100, height: 50, data: uint8clampedarray[20000] } filling a blank imagedata object this example creates and fills a new imagedata object with purple pixels. html <canvas id="canvas"></canvas> javascript since each pixel consists of four values, the for
loop iterates by multiples of four. the array values associated with each pixel are r (red), g (green), b (blue), and a (alpha), in that order. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 100); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // modify pixel data imagedata.dat...
CanvasRenderingContext2D.fillStyle - Web APIs
pattern a canvaspattern object (a repeating image). examples changing the fill color of a shape this example applies a blue fill color to a rectangle. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); result creating multiple fill colors using
loops in this example, we use two for
loops to draw a grid of rectangles, each having a different fill color. to achieve this, we use the two variables i and j to generate a unique rgb color for each square, and only modify the red and green values. (the blue channel has a fixed value.) by modifying the channels, you can generate all kinds of palettes. <canvas id="canvas" width="150" height="150"><...
CanvasRenderingContext2D.globalAlpha - Web APIs
llrect(50, 50, 100, 100); result overlaying transparent shapes this example illustrates the effect of overlaying multiple transparent shapes on top of each other. we begin by drawing a solid background composed of four differently colored squares. next, we set the globalalpha property to 0.2 (20% opaque); this alpha level will apply to all of our transparent shapes. after that, we use a for
loop to draw a series of circles with increasing radii. with each new circle, the opacity of the previous circles underneath is effectively increased. if we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image. <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getelementbyid('ca...
CanvasRenderingContext2D.strokeStyle - Web APIs
rn a canvaspattern object (a repeating image). examples changing the stroke color of a shape this example applies a blue stroke color to a rectangle. html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using
loops in this example, we use two for
loops and the arc() method to draw a grid of circles, each having a different stroke color. to achieve this, we use the two variables i and j to generate a unique rgb color for each circle, and only modify the green and blue values. (the red channel has a fixed value.) <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('c...
Manipulating video using canvas - Web APIs
thod to draw the current video frame into the context. the result is: line 3 fetches a copy of the raw graphics data for the current frame of video by calling the getimagedata() method on the first context. this provides raw 32-bit pixel image data we can then manipulate. line 4 computes the number of pixels in the image by dividing the total size of the frame's image data by four. the for
loop that begins on line 6 scans through the frame's pixels, pulling out the red, green, and blue values for each pixel, and compares the values against predetermined numbers that are used to detect the green screen that will be replaced with the still background image imported from foo.png. every pixel in the frame's image data that is found that is within the parameters that are considered to be pa...
Drawing shapes with canvas - Web APIs
rc anticlockwise; otherwise, the arc is drawn clockwise. note: angles in the arc function are measured in radians, not degrees. to convert degrees to radians you can use the following javascript expression: radians = (math.pi/180)*degrees. the following example is a little more complex than the ones we've seen above. it draws 12 different arcs all with different angles and fills. the two for
loops are for
looping through the rows and columns of arcs. for each arc, we start a new path by calling beginpath(). in the code, each of the parameters for the arc is in a variable for clarity, but you wouldn't necessarily do that in real life. the x and y coordinates should be clear enough. radius and startangle are fixed. the endangle starts at 180 degrees (half a circle) in the first column and ...
DOMTokenList.entries() - Web APIs
bject. the values are domstring objects, each representing a single token. syntax tokenlist.entries(); return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of
loop, writing them to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let iterator = classes.entries(); for (let value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment ...
DOMTokenList.keys() - Web APIs
s contained in this object. the keys are of type unsigned integer. syntax tokenlist.keys(); parameters none. return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of
loop, writing each one to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: var span = document.queryselector("span"); var classes = span.classlist; var iterator = classes.keys(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment dom...
DOMTokenList.values() - Web APIs
e domtokenlist. the individual values are domstring objects. syntax tokenlist.values(); parameters none. return value returns an iterator. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of
loop, writing each one to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: var span = document.queryselector("span"); var classes = span.classlist; var iterator = classes.values(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment d...
Element.classList - Web APIs
skippropchange = 1, target.classlist = restokenlist, target.classname = strval; skippropchange = 0, restokenlist.length = tokens.length - sub; } } function polyfillclasslist(ele){ if (!ele || !("innerhtml" in ele)) throw typeerror("illegal invocation"); ele.detachevent( "onpropertychange", whenpropchanges ); // prevent duplicate handler infinite
loop allowtokenlistconstruction = 1; try{ function protoobj(){} protoobj.prototype = new domtokenlist(); } finally { allowtokenlistconstruction = 0 } var protoobjproto = protoobj.prototype, restokenlist = new protoobj(); a: for(var toks=ele.classname.trim().split(wsre), ci=0, clen=toks.length, sub=0; ci !== clen; ++ci){ for (var inneri=0; inneri !== ...
Element.querySelectorAll() - Web APIs
tor("#userlist"); var matches = container.queryselectorall("li[data-active='1']"); accessing the matches once the nodelist of matching elements is returned, you can examine it just like any array. if the array is empty (that is, its length property is 0), then no matches were found. otherwise, you can simply use standard array notation to access the contents of the list. you can use any common
looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); note: nodelist is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc. to convert it into an array, try array.from(nodelist). user notes queryselectorall() behaves differently than most...
EventTarget.dispatchEvent() - Web APIs
was called, or if the event's type is null or an empty string. exceptions exceptions thrown by event handlers are reported as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event
loop, dispatchevent() invokes event handlers synchronously. all applicable event handlers will execute and return before the code continues on after the call to dispatchevent(). dispatchevent() is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model. the event can be created using event constructor. see also the event object re...
FormData.append() - Web APIs
ta, you can append multiple values with the same name. for example (and being compatible with php's naming conventions by adding [] to the name): formdata.append('userpic[]', myfileinput.files[0], 'chris1.jpg'); formdata.append('userpic[]', myfileinput.files[1], 'chris2.jpg'); this technique makes it simpler to process multi-file uploads because the resultant data structure is more conducive to
looping. if the sent value is different than string or blob it will be automatically converted to string: formdata.append('name', true); formdata.append('name', 74); formdata.append('name', 'john'); formdata.getall('name'); // ["true", "74", "john"] specifications specification status comment xmlhttprequestthe definition of 'append()' in that specification. living stan...
Using the Frame Timing API - Web APIs
a frame rate of 60 fps (frames per second) for a 60 hz refresh rate is a common target for a good responsive user experience. this means the browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer will have data about the duration of each frame event. ...
Frame Timing API - Web APIs
a frame rate of 60 fps (frames per second) for a 60 hz refresh rate is a common target for a good responsive user experience. this means the browser should process a frame in about 16.7 ms. an application can register a performanceobserver for "frame" performance entry types. ...
GlobalEventHandlers.onerror - Web APIs
ith a single argument of type event. a good example for this is when you are using an image tag, and need to specify a backup image in case the one you need is not available on the server for any reason. <img src="imagenotfound.gif" onerror="this.onerror=null;this.src='imagefound.gif';" /> the reason we have the this.onerror=null in the function is that the browser will be stuck in an endless
loop if the onerror image itself generates an error. notes when an error occurs in a script, loaded from a different origin, the details of the error are not reported to prevent leaking information (see bug 363897). instead the error reported is simply "script error." this behavior can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriat...
msAudioCategory - Web APIs
capablemedia"> </audio> the msaudiocategory property offers a variety of values that can enhance the behavior of your audio-aware app. note that you must set the msaudiocategory before setting the src property in code. value include a description of the property's value, including data type and what it represents. value description background capable? alert
looping or longer running alert sounds: alarms ring tones ringing notification sounds that need to attenuate existing audio no backgroundcapablemedia for audio that needs to continue playing in the background. examples include the following local media playback scenarios: local playlist streaming radio streaming playlist music v...
HTMLMediaElement - Web APIs
s nan. if the media is of indefinite length (such as streamed live media, a webrtc call's media, or similar), the value is +infinity. htmlmediaelement.ended read only returns a boolean that indicates whether the media element has finished playing. htmlmediaelement.error read only returns a mediaerror object for the most recent error, or null if there has not been an error. htmlmediaelement.
loop a boolean that reflects the
loop html attribute, which indicates whether the media element should start over when it reaches the end. htmlmediaelement.mediagroup a domstring that reflects the mediagroup html attribute, which indicates the name of the group of elements it belongs to. a group of media elements shares a common mediacontroller. htmlmediaelement.mediakeys read only returns a m...
Ajax navigation example - Web APIs
431: "request header fields too large", 500: "internal server error", 501: "not implemented", 502: "bad gateway", 503: "service unavailable", 504: "gateway timeout", 505: "http version not supported", 506: "variant also negotiates (experimental)", 507: "insufficient storage", 508: "
loop detected", 509: "unassigned", 510: "not extended", 511: "network authentication required" }; var oreq, bisloading = false, bupdateurl = false; oloadingbox.id = "ajax-loader"; ocover.onclick = abortreq; oloadingimg.src = "data:image/gif;base64,r0lgodlheaaqapiaap///waaamlcwkjcqgaaagjiyokcgpkskih/c05fvfndqvbfmi4waweaaaah/hpdcmvhd...
IDBCursor.advance() - Web APIs
bject store, then use a cursor to iterate through the records in the object store. here we use cursor.advance(2) to jump 2 places forward each time, meaning that only every other result will be displayed. advance() works in a similar way to idbcursor.continue, except that it allows you to jump multiple records at a time, not just always go onto the next record. note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function advanceresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(...
IDBCursor.continue() - Web APIs
invalidstateerror the cursor is currently being iterated or has iterated past its end. example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursor.delete() - Web APIs
gment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. if the albumtitle of the current cursor is "grace under pressure", we delete that entire record using var request = cursor.delete();. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function deleteresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readwrite'); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(...
IDBCursor.direction - Web APIs
e log the direction of the cursor, something like this: prev note: we can't change the direction of travel of the cursor using the direction property, as it is read-only. we specify the direction of travel using the 2nd argument of idbobjectstore.opencursor. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function backwards() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readonly'); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor(null,'prev').onsuccess = fu...
IDBCursor.key - Web APIs
e create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. within each iteration we log the key of the cursor to the console, something like this (its the album title in each case, which is our key). the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursor.primaryKey - Web APIs
eve an object store, then use a cursor to iterate through all the records in the object store. within each iteration we log the primary key of the cursor to the console, something like this (its the album title in each case, which is our primarykey): hemispheres the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursor.source - Web APIs
iteration we log the source of the cursor, which will log our idbobjectstore object to the console, something like this: idbobjectstore {autoincrement: false, transaction: idbtransaction, indexnames: domstringlist, keypath: "albumtitle", name: "rushalbumlist"…} the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursor.update() - Web APIs
he data. in such a situation, you would have to delete the record altogether and then add a new one using idbobjectstore.add. note also that you can't directly put cursor.value into an update call, hence the below example using an intermediary updatedata variable. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function updateresult() { list.innerhtml = ''; const transaction = db.transaction(['rushalbumlist'], 'readwrite'); const objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = funct...
IDBCursor - Web APIs
the first one iterated is retrieved. it starts at the upper bound of the key range and moves downwards. examples in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursorWithValue.value - Web APIs
value the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. within each iteration we log the value of the cursor with cursor.value. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IDBCursorWithValue - Web APIs
its parent interface, idbcursor. idbcursorwithvalue.value read only returns the value of the current cursor. example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. the cursor does not require us to select the data based on a key; we can just grab all of it. also note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo. for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor =...
IdleDeadline.timeRemaining() - Web APIs
turn. for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just return immediately, or look for other work to do with the remaining time. by the time timeremaining() reaches 0, it is suggested that the callback should return control to the user agent's event
loop. syntax timeremaining = idledeadline.timeremaining(); return value a domhighrestimestamp value (which is a floating-point number) representing the number of milliseconds the user agent estimates are left in the current idle period. the value is ideally accurate to within about 5 microseconds. if the idledeadline object's didtimeout property is true, this method returns zero. example see o...
ImageData.data - Web APIs
ues in all. let imagedata = new imagedata(100, 100); console.log(imagedata.data); // uint8clampedarray[40000] console.log(imagedata.data.length); // 40000 filling a blank imagedata object this example creates and fills a new imagedata object with colorful pixels. html <canvas id="canvas"></canvas> javascript since each pixel consists of four values within the data array, the for
loop iterates by multiples of four. the values associated with each pixel are r (red), g (green), b (blue), and a (alpha), in that order. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 100); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // percentage in the x direction, times 25...
Checking when a deadline is due - Web APIs
yone!) var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { next we create another indexeddb objectstore, and use the opencursor() method to open a cursor, which is basically a way in indexeddb to iterate through all the items in the store. we then
loop through all the items in the cursor for as long as there is a valid item left in the cursor. switch(cursor.value.month) { case "january": var monthnumber = 0; break; case "february": var monthnumber = 1; break; // other lines removed from listing for brevity case "december": var monthnumber = 11; ...
Timing element visibility with the Intersection Observer API - Web APIs
ed) using the performance.now() method. then we set visibleads back to previouslyvisibleads and set the latter to null. now the ads are all restarted, and configured to know that they became visible at the current time, so that they will not add up the duration of time the page was tabbed away the next time they're updated. handling intersection changes once per pass through the browser's event
loop, each intersectionobserver checks to see if any of its target elements have passed through any of the observer's intersection ratio thresholds. for each observer, a list of targets that have done so is compiled, and sent to the observer's callback as an array of intersectionobserverentry objects. our callback, intersectioncallback(), looks like this: function intersectioncallback(entries) { en...
Intersection Observer API - Web APIs
ites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages. reporting of visibility of advertisements in order to calculate ad revenues. deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result. implementing intersection detection in the past involved event handlers and
loops calling methods like element.getboundingclientrect() to build up the needed information for every element affected. since all this code runs on the main thread, even one of these can cause performance problems. when a site is loaded with these tests, things can get downright ugly. consider a web page that uses infinite scrolling. it uses a vendor-provided library to manage the advertisements pl...
KeyboardLayoutMap.entries - Web APIs
the entries read-only property of the keyboardlayoutmap interface returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well). syntax keyboardlayoutmap.entries() value an array of the given keyboardlayoutmap object's own enumerable property [key, value] pairs. specifications specification status comment keyboard mapthe definition of 'entries' in that specification. editor's draft initial definition. ...
KeyboardLayoutMap - Web APIs
of the the keyboard api is a map-like object with functions for retrieving the string associated with specific physical keys. a list of valid keys is found in the ui events keyboardevent code values specification. properties keyboardlayoutmap.entries read only returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well). keyboardlayoutmap.keys read only returns a new array iterator object that contains the keys for each index in the array. keyboardlayoutmap.size read only returns the number of elements in the keyboardlayoutmap object. keyboardlayoutmap.values read only returns a new array iterator objec...
Long Tasks API - Web APIs
/variable event handling latency. janky animations and scrolling. concepts some key terms or ideas that are utilized by the long tasks api. long task any uninterrupted period where the main ui thread is busy for 50 ms or longer. common examples include: long running event handlers. expensive reflows and other re-renders. work the browser does between different turns of the event
loop that exceeds 50 ms. culprit browsing context container the "culprit browsing context container", or "the container" for short, is the top level page, iframe, embed or object that the task occurred within. attributions a list of containers that the task occurred within. for tasks that don't occur within the top level page, the containerid, containername and containersrc fields may provide inf...
MediaDevices.ondevicechange - Web APIs
atedevices() on the mediadevices object referenced in the navigator.mediadevices property, as well as the code that's run when the promise returned by enumeratedevices() is fulfilled. the fulfillment handler is called when the device list is ready. the list is passed into the fulfillment handler as an array of mediadeviceinfo objects, each describing one media input or output device. a foreach()
loop is used to scan through all the devices. for each device, we create a new <li> object to be used to display it to the user. the line let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); deserves special notice. this uses destructuring assignment (a new feature of ecmascript 6) to assign the values of the first three items in the array returned by string.match() to the variabl...
Recording a media element - Web APIs
t is a start button and a <video> element which displays the video preview; this is the video the user's camera sees. note that the autoplay attribute is used so that as soon as the stream starts to arrive from the camera, it immediately gets displayed, and the muted attribute is specified to ensure that the sound from the user's microphone isn't output to their speakers, causing an ugly feedback
loop. <div class="right"> <div id="stopbutton" class="button"> stop </div> <h2>recording</h2> <video id="recording" width="160" height="120" controls></video> <a id="downloadbutton" class="button"> download </a> </div> on the right we see a stop button and the <video> element which will be used to play back the recorded video. notice that the playback panel doesn't have autoplay...
Navigator.sendBeacon() - Web APIs
ler. 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. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op
loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unl...
Node - Web APIs
calls a function for each descendant node of rootnode (including the root itself). if callback is omitted, the function returns an array instead, which contains rootnode and all nodes contained within. if callback is provided, and it returns boolean false when called, the current recursion level is aborted, and the function resumes execution at the last parent's level. this can be used to abort
loops once a node has been found (such as searching for a text node which contains a certain string). parameters rootnode the node object whose descendants will be recursed through. callback optional an optional callback function that receives a node as its only argument. if omitted, eachnode returns an array of every node contained within rootnode (including the root itself). sample usage t...
NodeList.length - Web APIs
the nodelist.length property returns the number of items in a nodelist. syntax numitems = nodelist.length numitems is an integer value representing the number of items in a nodelist. example the length property is often useful in dom programming. it's often used to test the length of a list, to see if it exists at all. it's also commonly used as the iterator in a for
loop, as in this example. // all the paragraphs in the document var items = document.getelementsbytagname("p"); // for each item in the list, // append the entire element as a string of html var gross = ""; for (var i = 0; i < items.length; i++) { gross += items[i].innerhtml; } // gross is now all the html for the paragraphs specifications specification status comment domthe definition...
OfflineAudioContext.startRendering() - Web APIs
etdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.
loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.st...
OfflineAudioContext - Web APIs
etdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.
loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering ...
ParentNode.replaceChildren() - Web APIs
s of the node tree are violated. examples emptying a node replacechildren() provides a very convenient mechanism for emptying a node of all its children. you simply call it on the parent node without any argument specified: mynode.replacechildren(); transferring nodes between parents replacechildren() enables you to easily transfer nodes between parents, without having to resort to verbose
looping code. for example, say we have a simple application allowing you to choose what food you want for your party. this html might look something like this: <h2>party food option list</h2> <main> <div> <label for="no">no thanks!</label> <select id="no" multiple size="10"> <option>apples</option> <option>oranges</option> <option>grapes</option> <option>bananas</o...
PaymentResponse.retry() - Web APIs
t. shippingaddress optional an addresserrors object which contains error messages for any of the fields in the shipping address that failed validation. return value a promise which is resolved when the payment is successfully completed. the promise is rejected with an appropriate exception value if the payment fails again. typically you will use this by calling show(), then entering a
loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request. if a retry is needed, the
loop calls retry(), then
loops back to check the response when it comes in. the
loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form,...
PerformanceFrameTiming - Web APIs
a frame rate of 60fps (frames per second) for a 60hz refresh rate is the target for a good responsive user experience. this means the browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer can retrieve data about the duration of each frame event. ...
Performance API - Web APIs
llowing a link, etc. interfaces performance provides methods and properties containing timing-related performance information for the given page. performanceentry provides methods and properties the encapsulate a single performance metric that is part of the performance timeline. performanceframetiming provides methods and properties containing frame timing data about the browser's event
loop. performancemark an abstract interface for performance entries with an entry type of "mark". entries of this type are created by calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline. performancemeasure an abstract interface for performance entries with an entry type of "measure". entries of this type are created by calling performance.
RTCDataChannel.bufferedAmount - Web APIs
to be sent over the data channel. the queue may build up as a result of calls to the send() method. this only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. 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. as messages are actually sent, this value is reduced accordingly. closing the data channel doesn't reset this count, even though the user agent purges the queued messages. however, even after closing the channel, attempts to send messages continue to add to the bufferedamount value, even though the messages are neither sent nor buffered. whenever this value decreases ...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
to or below this value, a bufferedamountlow event is fired. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. listeners may be added with onbufferedamountlow or addeventlistener(). 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. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. syntax var threshold = adatachannel.bufferedamountlowthreshold; adatachannel.bufferedamountlowthreshold = threshold; value the number of queued outgoing data bytes below which the buffer is considered to be "low." example in...
ResizeObserver - Web APIs
server interface reports changes to the dimensions of an element's content or border box, or the bounding box of an svgelement. note: the content box is the box in which content can be placed, meaning the border box minus the padding and border width. the border box encompasses the content, padding, and border. see the box model for further explanation. resizeobserver avoids infinite callback
loops and cyclic dependencies that are often created when resizing via a callback function. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and returns a new resizeobserver object. properties none. methods resize...
ScriptProcessorNode: audioprocess event - Web APIs
event handler property scriptprocessornode.onaudioprocess examples scriptnode.addeventlistener('audioprocess', function(audioprocessingevent) { // the input buffer is a song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; //
loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channel); var outputdata = outputbuffer.getchanneldata(channel); //
loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same a...
Using Service Workers - Web APIs
sed in a url to an image we wanted to load. in this version, we pass in a json fragment containing all the data for a single image (see what they look like in image-list.js). this is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. if you just passed in the url, and then tried to access the other items in the json separately when the for()
loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.) we actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34). promise...
SharedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
SharedWorkerGlobalScope - Web APIs
, when a messageport connection is opened between the associated sharedworker and the main thread. methods this interface inherits methods from the workerglobalscope interface, and its parent eventtarget, and therefore implements methods from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.close() discards any tasks queued in the sharedworkerglobalscope's event
loop, effectively closing this particular scope. inherited from workerglobalscope workerglobalscope.close() discards any tasks queued in the workerglobalscope's event
loop, effectively closing this particular scope. workerglobalscope.dump() allows you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. workerglobalscope.impor...
StylePropertyMapReadOnly - Web APIs
aration. retrieve an instance of this interface using element.computedstylemap(). properties stylepropertymapreadonly.size returns an unsinged long integer containing the size of the stylepropertymapreadonly object. methods stylepropertymapreadonly.entries() returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in
loop (the difference being that a for-in
loop enumerates properties in the prototype chain as well). stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly. stylepropertymapreadonly.get() returns the value of the specified property. stylepropertymapreadonly.getall() returns an array of cssstylevalue objects containing the values for the ...
StyleSheetList - Web APIs
the stylesheetlist interface represents a list of stylesheet. it is an array-like object but can't be iterated over using array methods. however it can be iterated over in a standard for
loop over its indices, or converted to an array. examples get document stylesheet objects with for
loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied. ignoring...', stylesheet.href); } }) .filter(boolean) .join('\n'); specifications specific...
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
nstances of the range of elements. note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too. syntax void gl.drawarraysinstanced(mode, first, count, instancecount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. inst...
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
es of a set of elements. note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too. syntax void gl.drawelementsinstanced(mode, count, type, offset, instancecount); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. po...
WebGL2RenderingContext.drawRangeElements() - Web APIs
the webgl2renderingcontext.drawrangeelements() method of the webgl api renders primitives from array data in a given range. syntax void gl.drawrangeelements(mode, start, end, count, type, offset); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. start a gluint specifying the minimum array index contained in offset. end a gluint specifying the maximum array index contained in offset. coun...
WebGLRenderingContext.drawArrays() - Web APIs
the webglrenderingcontext.drawarrays() method of the webgl api renders primitives from array data. syntax void gl.drawarrays(mode, first, count); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. first a glint specifying the starting index in the array of vector points. count a glsizei specifying the number of indices to be rendered. return value none. exceptions if mode is not one of ...
WebGLRenderingContext.drawElements() - Web APIs
the webglrenderingcontext.drawelements() method of the webgl api renders primitives from array data. syntax void gl.drawelements(mode, count, type, offset); parameters mode a glenum specifying the type primitive to render. possible values are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_
loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte g...
Raining rectangles - Web APIs
so on) organized in one place, and the overall code more compact and reusable. this example combines clearing the drawing buffer with solid colors and scissoring operations. it is a preview of a full graphical application that manipulates various phases of the webgl graphics pipeline and state machine. in addition, the example demonstrates how to integrate the webgl function calls within a game
loop. the game
loop is responsible for drawing the animation frames, and keeping the animation responsive to user input. here, the game
loop is implemented using timeouts. <p>you caught <strong>0</strong>. you missed <strong>0</strong>.</p> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; h...
Scissor animation - Web APIs
note that this time it is the position of the square (the scissoring area) that is updated every frame (we set frame rate to roughly one every 17ms, or roughly 60fps – frames per second). ...
WebGL constants - Web APIs
to webglrenderingcontext.drawelements() or webglrenderingcontext.drawarrays() to specify what kind of primitive to render. constant name value description points 0x0000 passed to drawelements or drawarrays to draw single points. lines 0x0001 passed to drawelements or drawarrays to draw lines. each vertex connects to the one after it. line_
loop 0x0002 passed to drawelements or drawarrays to draw lines. each set of two vertices is treated as a separate line segment. line_strip 0x0003 passed to drawelements or drawarrays to draw a connected group of line segments from the first vertex to the last. triangles 0x0004 passed to drawelements or drawarrays to draw triangles. each set of three vertices creates...
Matrix math for the web - Web APIs
d or memory management. these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection. in real production code it would be best to use optimized functions. glmatrix is an example of a library that has a focus on speed and performance. the focus in the glmatrix library is to have target arrays that are allocated before the update
loop. translation matrix a translation matrix is based upon the identity matrix, and is used in 3d graphics to move a point or object in one or more of the three directions (x, y, and/or z). the easiest way to think of a translation is like picking up a coffee cup. the coffee cup must be kept upright and oriented the same way so that no coffee is spilled. it can move up in the air off the table and...
Creating 3D objects using WebGL - Web APIs
l.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } define the vertices' colors we also need to build an array of colors for each of the 24 vertices. this code starts by defining a color for each face, then uses a
loop to assemble an array of all the colors for each of the vertices. const facecolors = [ [1.0, 1.0, 1.0, 1.0], // front face: white [1.0, 0.0, 0.0, 1.0], // back face: red [0.0, 1.0, 0.0, 1.0], // top face: green [0.0, 0.0, 1.0, 1.0], // bottom face: blue [1.0, 1.0, 0.0, 1.0], // right face: yellow [1.0, 0.0, 1.0, 1.0], // left face: pur...
Writing WebSocket servers - Web APIs
igned integer. (the most significant bit must be 0.) you're done. reading and unmasking the data if the mask bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. once the payload length and masking key is decoded, you can read that number of bytes from the socket. let's call the data encoded, and the key mask. to get decoded,
loop through the octets (bytes a.k.a. characters for text data) of encoded and xor the octet with the (i modulo 4)th octet of mask. in pseudo-code (that happens to be valid javascript): var decoded = ""; for (var i = 0; i < encoded.length; i++) { decoded[i] = encoded[i] ^ mask[i % 4]; } now you can figure out what decoded means depending on your application. message fragmentation the fin and o...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
gl.color_buffer_bit in the mask parameter) and the depth buffer (because we include gl.depth_buffer_bit). then we determine how much time has elapsed since the previous frame was rendered by comparing the frame's desired render time with the time at which the last frame was drawn. since this value is in microseconds, we convert it to seconds by multiplying by 0.001 (or diiding by 1000).. now we
loop over the pose's views, as found in the xrviewerpose array, views. for each view, we ask the xrwebgllayer for the appropriate viewport to use, configure the webgl viewport to match by passing the position and size information into gl.viewport(). this constrains rendering so that we can only draw into the portion of the framebuffer that represents the image seen by the eye identified by view.eye. ...
WebXR application life cycle - Web APIs
s located in the 3d world to render the frame using webgl. each time the callback is invoked, it should call requestanimationframe() again in order to let the browser know that the callback needs to be run again when it's time to render the next frame. when the time comes (such as when the user exits your app or navigates away from your site), end the xr session; otherwise, continue the
loop until the user chooses to exit xr mode. to end the xr session yourself, call xrsession.end(). include a handler for the xrsession event end event to be informed when the session is ending, regardless of whether your code, the user, or the browser initiated the termination of the session. ...
Starting up and shutting down a WebXR session - Web APIs
state) { case "hidden": myframerate = 10; break; case "blurred-visible": myframerate = 30; break; case "visible": default: myframerate = 60; break; } }; this example changes a variable myframerate depending on the visibility state as it changes. presumably the renderer uses this value to compute how often to render new frames as the animation
loop progresses, thus rendering less frequently the more "blurred" the scene becomes. detecting reference space resets occasionally, discontinuities or jumps in the native origin may occur while tracking the user's position in the world. the most common scenarios in which this happens are when the user requests a recalibration of their xr device or when a hiccup or glitch occurs in the flow of track...
Web Animations API Concepts - Web APIs
works so you can use it effectively. to learn how to put the api to use, check out its sister article, using the web animations api. the web animations api fills the gap between declarative css animations and transitions, and dynamic javascript animations. this means we can use it to create and manipulate css-like animations that go from one pre-defined state to another, or we can use variables,
loops, and callbacks to create interactive animations that adapt and react to changing inputs. history over a decade ago, synchronized multimedia integration language, or smil (pronounced "smile"), brought animation to svg. back then it was the only animation engine browsers had to worry about. while four out of five browsers supported smil, it only animated svg elements, could not be used from css,...
Using IIR filters - Web APIs
sctx.font = fontsize+'px sans-serif'; canvasctx.fillstyle = 'grey'; canvasctx.filltext('1', spacing-fontsize, spacing+fontsize); canvasctx.filltext('g', spacing-fontsize, (height-spacing+fontsize)/2); canvasctx.filltext('0', spacing-fontsize, height-spacing+fontsize); canvasctx.filltext('hz', width/2, height-spacing+fontsize); canvasctx.filltext('20k', width-spacing, height-spacing+fontsize); //
loop over our magnitude response data and plot our filter canvasctx.beginpath(); for(let i = 0; i < magresponseoutput.length; i++) { if (i === 0) { canvasctx.moveto(spacing, height-(magresponseoutput[i]*100)-spacing ); } else { canvasctx.lineto((width/totalarrayitems)*i, height-(magresponseoutput[i]*100)-spacing ); } } canvasctx.stroke(); summary that's it for our i...
Using the Web Speech API - Web APIs
rate'); var ratevalue = document.queryselector('.rate-value'); var voices = []; populating the select element to populate the <select> element with the different voice options the device has available, we've written a populatevoicelist() function. we first invoke speechsynthesis.getvoices(), which returns a list of all the available voices, represented by speechsynthesisvoice objects. ...
Window: popstate event - Web APIs
into account that properties like window.location will already reflect the state change (if it affected the current url), but document might still not. if the goal is to catch the moment when the new document state is already fully in place, a zero-delay settimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event
loop: window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstate event is near the end of the process to transition to the new location. it happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, bu...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
ng settimeout(). for example, if using setinterval() to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. as such, you may find yourself with queued up xhr requests that won't necessarily return in order. in these cases, a recursive settimeout() pattern is preferred: (function
loop(){ settimeout(function() { // your logic here
loop(); }, delay); })(); in the above snippet, a named function
loop() is declared and is immediately executed.
loop() is recursively called inside settimeout() after the logic has completed executing. while this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed bef...
WorkerGlobalScope.close() - Web APIs
the close() method of the workerglobalscope interface discards any tasks queued in the workerglobalscope's event
loop, effectively closing this particular scope. syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. ...
XRInputSource.gripSpace - Web APIs
h that represents the position and orieintation of the controller in the virtual environment. for (let source in xrsession.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, xrrefspace); if (grippose) { mydrawmeshusingtransform(controllermesh, grippose.transform.matrix); } } } for each input source which has a value for gripspace, this
loop obtains the xrpose representing the position and orientation that are described by gripspace. if a valid pose is returned, a method mydrawmeshusingtransform() is called to draw the controller's mesh transformed using the grip pose's transform matrix. specifications specification status comment webxr device apithe definition of 'xrinputsource.gripspace' in that specifica...
XRInputSourceArray.values() - Web APIs
source objects in the array, starting with the first entry (at index 0) and proceeding straight through the list. examples this example snippet walks through each input and calls the function checkinput() with each returned value. for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. each pass through the
loop, source is the next xrinputsource in the list. the
loop exits once every input has been delivered to checkinput(). specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for...
XRSession.onvisibilitychange - Web APIs
the onvisibilitychange attribute of the xrsession object is the event handler for the visibilitychange event, which is dispatched when the visibility state of the xr session changes. the visibility state of the session is accessible via xrsession.visibilitystate. note: the visibility state of xr session affects the frame
loop so callbacks registered via xrsession.requestanimationframe() might not be called. consult xrsession.visibilitystate article for details. syntax xrsession.onvisibilitychange = function(event) { ... } example xrsession.onvisibilitychange = function(event) { console.log("the visibility the xr session changed.") } specifications specification status comment webxr device apithe definition of 'xrsession.onvisibilitychange' i...
XRSystem: requestSession() - Web APIs
securityerror permission to enter the specified xr mode is denied. this can happen for a number of reasons, which are covered in more detail in permissions and security in webxr device api. examples creating an immersive vr session the following example calls requestsession() requesting an "immersive-vr" session. if the promise resolves, it sets up a session and initiates the animation
loop. navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', onxrsessionended); // do necessary session setup here. // begin the session’s animation
loop. xrsession.requestanimationframe(onxranimationframe); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occur...
XRView.transform - Web APIs
then we iterate over each xrview found in the xrviewerpose's list of views. there will usually be two: one for the left eye and one for the right, but there may be only one if in monoscopic mode. currently, webxr doesn't support more than two views...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
nting a rendering surface we can use for the xrsession; we set it as the rendering surface for xrsession by calling its updaterenderstate() method, passing the new gllayer in using the xrrenderstate dictionary's xrrenderstate.baselayer property. the result is a rendering context that looks like the diagram below: each time the xrviewerpose's views are iterated over for rendering, the rendering
loop obtains an xrview for the left eye which has its top-left corner at (0, 0) with its width and height being 1280x1440 pixels. the right eye it obtains has its top-left corner at 1280, 0 with the same width and height: 1280x1440. specifications specification status comment webxr device apithe definition of 'static xrwebgllayer.getnativeframebufferscalefactor()' in that spe...
Web accessibility for seizures and physical reactions - Accessibility
legibility. putting the amount of contrast in the user's control is a definite gift for accessibility. prefers-reduced-transparency the prefers-reduced-transparency media feature is used to detect if the user has requested the system minimize the amount of transparent or translucent layer effects it uses. mediaquerylist interface section 4.2 from the csswg.org drafts integrates with the event
loop defined in html. [html] for the mediaquerylist object. see the mdn document, mediaquerylist for more information. personalization help and support the requirement for the literal property is taken from section 23 non-literal text and images requirement: some users cannot understand non-literal text and icons such as metaphors, idioms etc. the literal property is intended to identify text or im...
system - CSS: Cascading Style Sheets
*/ system: fixed 3; system: extends decimal; this may take one of three forms: one of the keyword values cyclic, numeric, alphabetic, symbolic, additive, or fixed. the keyword value fixed along with an integer. the keyword value or extends along with a @counter-style name. cyclic cycles through the list of symbols provided. once the end of the list of symbols is reached, it will
loop back to the beginning and start over. this system is useful for simple bullet styles with just one symbol, or for styles having multiple symbols. at least one symbol must be specified in the symbols descriptor, or the counter style is not valid. fixed defines a finite set of symbols are specified. once the system has
looped through all the specified symbols, it will fall back. this system is us...
Detecting CSS animation support - CSS: Cascading Style Sheets
xes[ i ]; animationstring = pfx + 'animation'; keyframeprefix = '-' + pfx.tolowercase() + '-'; animation = true; break; } } } for starters we define a few variables. we assume that animation is not supported by setting animation to false. we set the animationstring to animation which is the property we want to set later on. we create an array of browser prefixes to
loop over and we set pfx to an empty string. then we check if the css animation-name property on the style collection for the element specified by the variable elem is set. this means the browser supports css animation without any prefix, which, to date, none of them do. if the browser does not support non-prefixed animation and animation is still false, we iterate over all the possible prefixes, si...
Using CSS transitions - CSS: Cascading Style Sheets
defining transitions css transitions are controlled using the shorthand transition property. 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. you can control the individual components of the transition with the following sub-properties: (note that these transitions
loop infinitely only for the purpose of our examples; css transitions only visualize a property change from start to finish. if you need visualizations that
loop, look into the css animation property.) transition-property specifies the name or names of the css properties to which transitions should be applied. only properties listed here are animated during transitions; changes to all other proper...
Adding captions and subtitles to HTML5 video - Developer guides
need to do is store a handle to the subtitles' button: var subtitles = document.getelementbyid('subtitles'); we also initially turn off all subtitles, in case the browser turns any of them on by default: for (var i = 0; i < video.texttracks.length; i++) { video.texttracks[i].mode = 'hidden'; } the video.texttracks property contains an array of all the text tracks attached to the video. we
loop through each one and set its mode to hidden. note: the webvtt api gives us access to all the text tracks that are defined for an html5 video using the <track> element. building a caption menu our aim is to use the subtitles button we added earlier to display a menu that allows users to choose which language they want the subtitles displayed in, or to turn them off entirely. we have added th...
Cross-browser audio basics - Developer guides
action — in short, the audio will autoplay. <audio autoplay> ... </audio> note: this value is often ignored on mobile platforms, and its use is not recommended unless really necessary. auto-playing audio (and video) is usually really annoying. plus browsers have policies that will block autoplay entirely in many situations. see the autoplay guide for media and web audio apis for details.
loop the
loop attribute will ensure that upon getting to the end of the audio clip, the audio clip will
loop back to the beginning and start playing again. <audio
loop> ... </audio> muted if you want the audio to start muted (no volume), add the muted attribute. <audio muted> ... </audio> note: this value is often ignored on mobile platforms. preload the preload attribute allows you to s...
Media events - Developer guides
the time you receive the event. pause sent when the playback state is changed to paused (paused property is true). play sent when the playback state is no longer paused, as a result of the play method, or the autoplay attribute. playing sent when the media has enough data to start playing, after the play event, but also when recovering from being stalled, when
looping media restarts, and after seeked, if it was playing before seeking. progress sent periodically to inform interested parties of progress downloading the media. information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a se...
HTML attribute reference - HTML: Hypertext Markup Language
ines the language used in the element. language <script> defines the script language used in the element. loading <img>, <iframe> indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager"). wip: whatwg pr #3752 list <input> identifies a list of pre-defined options to suggest to the user.
loop <audio>, <bgsound>, <marquee>, <video> indicates whether the media should start playing from the start when it's finished. low <meter> indicates the upper bound of the lower range. manifest <html> specifies the url of the document's cache manifest. note: this attribute is obsolete, use <link rel="manifest"> instead. max <input>, <meter>, <pr...
Index - HTTP
ver. it is used by the server to indicate which headers it used when selecting a representation of a resource in a content negotiation algorithm. 113 via http, reference, header the via general header is added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers. it is used for tracking message forwards, avoiding request
loops, and identifying the protocol capabilities of senders along the request/response chain. 114 www-authenticate http, http header, reference, response header, header the http www-authenticate response header defines the authentication method that should be used to gain access to a resource. 115 warning general header, http, reference, header the warning gen...
Via - HTTP
header type general header forbidden header name yes syntax via: [ <protocol-name> "/" ] <protocol-version> <host> [ ":" <port> ] or via: [ <protocol-name> "/" ] <protocol-version> <pseudonym> directives <protocol-name> optional. ...
TRACE - HTTP
the final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message body of a 200 (ok) response with a content-type of message/http. the final recipient is either the origin server or the first server to receive a max-forwards value of 0 in the request. ...
HTTP request methods - HTTP
hod replaces all current representations of the target resource with the request payload. delete the delete method deletes the specified resource. connect the connect method establishes a tunnel to the server identified by the target resource. options the options method is used to describe the communication options for the target resource. trace the trace method performs a message
loop-back test along the path to the target resource. patch the patch method is used to apply partial modifications to a resource. specifications specification title comment rfc 7231, section 4: request methods hypertext transfer protocol (http/1.1): semantics and content specifies get, head, post, put, delete, connect, options, trace. rfc 5789, section 2:...
Network Error Logging - HTTP
vered by previous errors http.error the user agent successfully received a response, but it had a 4xx or 5xx status code http.protocol.error the connection was aborted due to an http protocol error http.response.invalid response is empty, has a content-length mismatch, has improper encoding, and/or other conditions that prevent user agent from processing the response http.response.redirect_
loop the request was aborted due to a detected redirect
loop http.failed the connection failed due to errors in http protocol not covered by previous errors specifications specification network error logging ...
414 URI Too Long - HTTP
the http 414 uri too long response status code indicates that the uri requested by the client is longer than the server is willing to interpret. there are a few rare conditions when this might occur: when a client has improperly converted a post request to a get request with long query information, when the client has descended into a
loop of redirection (for example, a redirected uri prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit potential security holes. status 414 uri too long specifications specification title rfc 7231, section 6.5.12: 414 uri too long hypertext transfer protocol (http/1.1): semantics and content ...
HTTP response status codes - HTTP
server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. 507 insufficient storage (webdav) the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. 508
loop detected (webdav) the server detected an infinite
loop while processing the request. 510 not extended further extensions to the request are required for the server to fulfil it. 511 network authentication required the 511 status code indicates that the client needs to authenticate to gain network access. ...
About JavaScript - JavaScript
ontrolling web page behavior. contrary to popular misconception, javascript is not "interpreted java". in a nutshell, javascript is a dynamic scripting language supporting prototype based object construction. the basic syntax is intentionally similar to both java and c++ to reduce the number of new concepts required to learn the language. language constructs, such as if statements, for and while
loops, and switch and try ... catch blocks function the same as in these languages (or nearly so). javascript can function as both a procedural and an object oriented language. objects are created programmatically in javascript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like c++ and java. once...
Expressions and operators - JavaScript
ld use a standard operator. for example, var status = (age >= 18) ? 'adult' : 'minor'; this statement assigns the value "adult" to the variable status if age is eighteen or more. otherwise, it assigns the value "minor" to status. comma operator the comma operator (,) simply evaluates both of its operands and returns the value of the last operand. this operator is primarily used inside a for
loop, to allow multiple variables to be updated each time through the
loop. it is regarded bad style to use it elsewhere, when it is not necessary. often two separate statements can and should be used instead. for example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. the code prints the values of the diagonal ele...
Grammar and types - JavaScript
literal, namely template literals. this allows for many new features, including multiline strings! var poem = `roses are red, violets are blue. sugar is sweet, and so is foo.` more information this chapter focuses on basic syntax for declarations and types. to learn more about javascript's language constructs, see also the following chapters in this guide: control flow and error handling
loops and iteration functions expressions and operators in the next chapter, we will have a look at control flow constructs and error handling. « previousnext » ...
Keyed collections - JavaScript
s contain elements which are iterable in the order of insertion. maps map object ecmascript 2015 introduces a new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. you can use a for...of
loop to return an array of [key, value] for each iteration. let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' +...
Working with objects - JavaScript
object.keys(o) this method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o. object.getownpropertynames(o) this method returns an array containing all own properties' names (enumerable or not) of an object o. before ecmascript 5, there...
JavaScript Guide - JavaScript
his guide is divided into several chapters: introduction about this guide about javascript javascript and java ecmascript tools hello world grammar and types basic syntax & comments declarations variable scope variable hoisting data structures and types literals control flow and error handling if...else switch try/catch/throw error objects
loops and iteration for while do...while break/continue for..in for..of functions defining functions calling functions function scope closures arguments & parameters arrow functions expressions and operators assignment & comparisons arithmetic operators bitwise & logical operators conditional (ternary) operator numbers and dates number literals...
The legacy Iterator protocol - JavaScript
the deprecated firefox-only iterator protocol firefox, prior to version 26 implemented another iterator protocol that is similar to the standard es2015 iterator protocol. an object is an legacy iterator when it implements a next() method with the following semantics, and throws stopiteration at the end of iteration. property value next a zero arguments function that returns an value. ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
ew date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.tolocaledatestring('de-de', options); console.log(date); // "freitag, 10. märz 2017" or, you can make use of the intl.datetimeformat object, which allows you to cache an object with most of the computations done so that formatting is fast. this is useful if you have a
loop of dates to format. var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateformatter = new intl.datetimeformat('de-de', options) var dates = [date.utc(2012, 11, 20, 3, 0, 0), date.utc(2014, 04, 12, 8, 0, 0)]; dates.foreach(date => console.log(dateformatter.format(date))); // "donnerstag, 20. dezember 2012" // "montag, 12. mai 20...
arguments[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the array.prototype.values property. syntax arguments[symbol.iterator]() examples iteration using for...of
loop function f() { // your browser must support for..of
loop // and let-scoped variables in for
loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification. ecmascript (ecma-262)the definition of 'createmappedargumentsobject' in that specification. ...
Array.prototype.reduce() - JavaScript
currentvalue) { if (accumulator.indexof(currentvalue) === -1) { accumulator.push(currentvalue) } return accumulator }, []) console.log(myorderedarray) replace .filter().map() with .reduce() using array.filter() then array.map() traverses the array twice, but you can achieve the same effect while traversing only once with array.reduce(), thereby being more efficient. (if you like for
loops, you can filter and map while traversing once with array.foreach()). const numbers = [-5, 6, 2, 0,]; const doubledpositivenumbers = numbers.reduce((accumulator, currentvalue) => { if (currentvalue > 0) { const doubled = currentvalue * 2; accumulator.push(doubled); } return accumulator; }, []); console.log(doubledpositivenumbers); // [12, 4] running promises in sequence /** * ...
Array.prototype.entries() - JavaScript
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax array.entries() return value a new array iterator object. examples iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of
loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.entries' in that specification. ...
Array.prototype.length - JavaScript
o configurable no writable: if this attribute set to false, the value of the property cannot be changed. configurable: if this attribute set to false, any attempts to delete the property or change its attributes (writable, configurable, or enumerable) will fail. enumerable: if this attribute set to true, the property will be iterated over during for or for..in
loops. examples iterating over an array in the following example, the array numbers is iterated through by looking at the length property. the value in each element is then doubled. var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] *= 2; } // numbers is now [2, 4, 6, 8, 10] shortening an array the following example shortens the array n...
Array.prototype.map() - JavaScript
/ reformattedarray is now [{1: 10}, {2: 20}, {3: 30}], // kvarray is still: // [{key: 1, value: 10}, // {key: 2, value: 20}, // {key: 3, value: 30}] mapping an array of numbers using a function containing an argument the following code shows how map works when a function requiring one argument is used with it. the argument will automatically be assigned from each element of the array as map
loops through the original array. let numbers = [1, 4, 9] let doubles = numbers.map(function(num) { return num * 2 }) // doubles is now [2, 8, 18] // numbers is still [1, 4, 9] using map generically this example shows how to use map on a string to get an array of bytes in the ascii encoding representing the character values: let map = array.prototype.map let a = map.call('hello world', funct...
Array.prototype.unshift() - JavaScript
ty—reflecting the last in a series of consecutive, zero-based numerical properties—may not behave in any meaningful manner. please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. hence, calling unshift with n arguments once, or calling it n times with 1 argument (with a
loop, for example), don't yield the same results. see example: let arr = [4, 5, 6] arr.unshift(1, 2, 3) console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6] // resetting the array arr.unshift(1) arr.unshift(2) arr.unshift(3) console.log(arr) // [3, 2, 1, 4, 5, 6] examples using unshift let arr = [1, 2] arr.unshift(0) // result of the call is 3, which is the new array length...
Array - JavaScript
the array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties. ...
Function.caller - JavaScript
examples checking the value of a function's caller property the following code checks the value a function's caller property. function myfunc() { if (myfunc.caller == null) { return 'the function was called from the top!'; } else { return 'this function\'s caller was ' + myfunc.caller; } } specifications not part of any standard. ...
InternalError - JavaScript
ed from error. internalerror.prototype.linenumber line number in file that raised this error. inherited from error. internalerror.prototype.columnnumber column number in line that raised this error. inherited from error. internalerror.prototype.stack stack trace. inherited from error. examples too much recursion this recursive function runs 10 times, as per the exit condition. function
loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do stuff
loop(x + 1); // the recursive call }
loop(0); setting this condition to an extremely high value, won't work: function
loop(x) { if (x >= 1000000000000) return; // do stuff
loop(x + 1); }
loop(0); // internalerror: too much recursion for more information, see internalerror: too much recursion. specifi...
Object.freeze() - JavaScript
-strict mode employee.address.city = "noida"; // attributes of child object can be modified console.log(employee.address.city) // output: "noida" to make an object immutable, recursively freeze each property which is of type object (deep freeze). use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless
loop will be triggered. an enhancement to deepfreeze() would be to have an internal function that receives a path (e.g. an array) argument so you can suppress calling deepfreeze() recursively when an object is in the process of being made immutable. you still run a risk of freezing an object that shouldn't be frozen, such as [window]. function deepfreeze(object) { // retrieve the property names de...
Object.prototype.hasOwnProperty() - JavaScript
pe chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties. note that the for...in
loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the
loop that hasownproperty itself is confined strictly to enumerable items (as with object.getownpropertynames()). var buz = { fog: 'stack' }; for (var name in buz) { if (buz.hasownproperty(name)) { console.log('this is fog (' + name + ') for sure. value: ...
Object.prototype.propertyIsEnumerable() - JavaScript
send us a pull request. syntax obj.propertyisenumerable(prop) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in
loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property, this method returns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // ret...
Promise.prototype.then() - JavaScript
unction called if the promise is rejected. this function has one argument, the rejection reason. if it is not a function, it is internally replaced with a "thrower" function (it throws an error it received as argument). 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). the behavior of the handler function follows a specific set of rules. if a handler function: returns a value, the promise returned by then gets resolved with the returned value as its value. doesn't return anything, the promise returned by then gets resolved with an undefined value. throws an error, the promise returned by then gets rejected with the thrown error as its value. returns an ...
RegExp() constructor - JavaScript
pressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a
loop, the regular expression won't be recompiled on each iteration. the constructor of the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. specifica...
RegExp.prototype.exec() - JavaScript
yarray = myre.exec(str)) !== null) { let msg = 'found ' + myarray[0] + '. '; msg += 'next match starts at ' + myre.lastindex; console.log(msg); } this script displays the following text: found abb. next match starts at 3 found ab. next match starts at 9 warning: do not place the regular expression literal (or regexp constructor) within the while condition! it will create an infinite
loop if there is a match, due to the lastindex property being reset upon each iteration. also, be sure that the global flag ("g") is set, or it will also cause an infinite
loop. using exec() with regexp literals you can also use exec() without creating a regexp object explicitly: let matches = /(hello \s+)/.exec('this is a hello world!'); console.log(matches[1]); this will log a message contain...
RegExp - JavaScript
pressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated. use literal notation when the regular expression will remain constant. for example, if you use literal notation to construct a regular expression used in a
loop, the regular expression won't be recompiled on each iteration. the constructor of the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and obtain it from another source, such as user input. flags in const...
String.prototype.substring() - JavaScript
a better method for replacing strings is as follows: function replacestring(olds, news, fulls) { return fulls.split(olds).join(news) } the code above serves as an example for substring operations. if you need to replace substrings, most of the time you will want to use string.p...
Image file type and format guide - Web media technologies
of visually similar compression levels. lossless webp images are typically 26% smaller than the same images in png format. webp also supports animation: in a lossy webp file, the image data is represented by a vp8 bitstream, which may contain multiple frames. lossless webp holds the anim chunk, which describes the animation, and the anmf chunk, which represents a frame of an animation sequence.
looping is supported. webp now has broad support in the latest versions of major web browsers, although it does not have deep historical support. provide a fallback in either jpeg or png format, such as with the <picture> element. mime type image/webp file extension(s) .webp specification riff container specification rfc 6386: vp8 data format and decodin...
CSS and JavaScript animation performance - Web Performance
questanimationframe() api provides an efficient way to make animations in javascript. the callback function of the method is called by the browser before the next repaint on each frame. compared to settimeout()/setinterval(), which need a specific delay parameter, requestanimationframe() is much more efficient. developers can create an animation by simply changing an element's style each time the
loop is called (or updating the canvas draw, or whatever.) note: like css transitions and animations, requestanimationframe() pauses when the current tab is pushed into the background. for more details read animating with javascript from setinterval to requestanimationframe. performance comparison: transitions vs. requestanimationframe the fact is that, in most cases, the performance of css-bas...
Web Performance
ithin applications. together, these interfaces can be used to help identify an application's performance bottlenecks. user timing api create application specific timestamps using the user timing api's "mark" and "measure" entry types - that are part of the browser's performance timeline. frame timing api the performanceframetiming interface provides frame timing data about the browser's event
loop. 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. other documentation developer tools performance features this section provides information on how to use and understand ...
Progressive loading - Progressive web apps (PWAs)
st loadimages = (image) => { image.setattribute('src', image.getattribute('data-src')); image.onload = () => { image.removeattribute('data-src'); }; }; the imagestoload variable contains references to all the images, while the loadimages function moves the path from data-src to src. when each image is actually loaded, we remove its data-src attribute as it's not needed anymore. then we
loop through each image and load it: imagestoload.foreach((img) => { loadimages(img); }); blur in css to make the whole process more visually appealing, the placeholder is blurred in css. we render the images with a blur at the beginning, so a transition to the sharp one can be achieved: article img[data-src] { filter: blur(0.2em); } article img { filter: blur(0em); transition: filter ...
begin - SVG: Scalable Vector Graphics
oke-width=".5" /> </svg> begin-3-event.svg repeat example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- animated rectangle --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" from="0" to="100" id="my
loop" begin="0s;my
loop.end" dur="4s" repeatcount="3" /> <set attributetype="css" attributename="fill" to="green" begin="my
loop.begin" /> <set attributetype="css" attributename="fill" to="gold" begin="my
loop.repeat(1)" /> <set attributetype="css" attributename="fill" to="red" begin="my
loop.repeat(2)" /> </rect> ...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
s unknown deprecated xml:space attribute implementation status unknown kerning property removed implementation status unknown path attribute for <textpath> implemented (bug 1446617) reference basic shapes to <textpath> implementation status unknown side attribute for <textpath> implemented (bug 1446650) render characters for one
loop of a single closed path, effected by the startoffset attribute and text-anchor property implementation status unknown <tref> removed implementation status unknown <altglyph>, <altglyphdef>, <altglyphitem> and <glyphref> removed <altglyph>, <altglyphdef> and <altglyphitem> removed (bug 1260032), <glyphref> never really implemented (bug 1302693) svgtextcontentele...
SVG animation with SMIL - SVG: Scalable Vector Graphics
e left and right edges of a black box, over and over again, indefinitely. the animation here is handled by the <animatemotion> element. in this case, we're establishing a path consisting of a moveto command to establish the starting point for the animation, then the horizontal-line command to move the circle 300 pixels to the right, followed by the z command, which closes the path, establishing a
loop back to the beginning. by setting the value of the repeatcount attribute to indefinite, we indicate that the animation should
loop forever, as long as the svg image exists. <svg xmlns="http://www.w3.org/2000/svg" width="300" height="100"> <title>svg smil animate with path</title> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <circle cx="0" cy="50" r="15" fil...
Fills and Strokes - SVG: Scalable Vector Graphics
d (whitespace is ignored). the first number specifies a distance for the filled area, and the second a distance for the unfilled area. so in the above example, the second path fills 5 pixel units, with 5 blank units until the next dash of 5 units. you can specify more numbers if you would like a more complicated dash pattern. the first example specifies three numbers, in which case the renderer
loops the numbers twice to create an even pattern. so the first path renders 5 filled, 10 empty, 5 filled, and then
loops back to create 5 empty, 10 filled, 5 empty. the pattern then repeats. there are additional stroke and fill properties available, including fill-rule, which specifies how to color in shapes that overlap themselves; stroke-miterlimit, which determines if a stroke should draw miters;...
Tutorials
taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements,
loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. getting started with javascript what is javascript and how can it help you? codecademy codecademy is an easy way to learn how to code javascript. it's interactive and you can do it with your friends. freecodecamp freecodecamp teaches a variety of languag...