Search completed in 0.85 seconds.
Looping code - Learn web development
here we'll look at the
loop structures available in javascript that handle such needs.
... objective: to understand how to use
loops in javascript.
... keep me in the
loop loops,
loops,
loops.
...And 70 more matches
Loops and iteration - JavaScript
« previousnext »
loops offer a quick and easy way to do something repeatedly.
... 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.
...And 32 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.
...we didn't provide live editable versions of these tasks because of the risk of creating infinite
loops and crashing the assessment page!
...
loops 1 in our first
looping task we want you start by creating a simple
loop that goes through all the items in the provided myarray and prints them out on the screen inside list items (i.e., <li> elements), which are appended to the provided list.
...And 7 more matches
AudioBufferSourceNode.loopEnd - Web APIs
the
loopend property of the audiobuffersourcenode interface specifies is a floating point number specifying, in seconds, at what offset into playing the audiobuffer playback should
loop back to the time indicated by the
loopstart property.
... this is only used if the
loop property is true.
... syntax audiobuffersourcenode.
loopend = endoffsetinseconds; var endoffsetinseconds = audiobuffersourcenode.
loopend; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each
loop will
loop return to the beginning of the
loop (that is, the current play time gets reset to audiobuffersourcenode.
loopstart).
...And 6 more matches
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.
...And 6 more matches
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.
...And 5 more matches
Concurrency model and the event loop - JavaScript
javascript has a concurrency model based on an event
loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
... at some point during the event
loop, the runtime starts handling the messages on the queue, starting with the oldest one.
...then, the event
loop will process the next message in the queue (if there is one).
...And 5 more matches
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
the javascript strict mode-only exception "for-in
loop head declarations may not have initializers" occurs when the head of a for...in contains an initializer expression, such as |for (var i = 0 in obj)|.
... this is not allowed in for-of
loops in strict mode.
... message syntaxerror: for-in
loop head declarations cannot have an initializer (edge) syntaxerror: for-in
loop head declarations may not have initializers (firefox) syntaxerror: for-in
loop variable declaration may not have an initializer.
...And 5 more matches
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.
...And 5 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.
... 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.
... 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).
...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?
... 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 inside the
loop: var object = { a: 10, b: 20 }; for (var key in object) { var x = object[key]; console.log(x); // 10 // 20 } or, using for...of (es2015) and object.values (es2017), you can get an array of the specified object values and iterate over the array like this: var object = { a: 10, b: 20 }...
...And 2 more matches
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.
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".
... status 508
loop detected specifications specification title rfc 5842, section 7.2: 508
loop detected web distributed authoring and versioning ...
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.
...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).
...the game
loop is advanced by the user's input and sleeps until they provide it.
...And 39 more matches
Index - Web APIs
116 audiobuffersourcenode.
loop api, audio, audiobuffersourcenode,
loop, media, property, reference, web audio api, sound the
loop property's default value is false.
... 117 audiobuffersourcenode.
loopend api, audio, audiobuffersourcenode, media, property, reference, web audio api,
loopend, sound a floating-point number indicating the offset, in seconds, into the audio buffer at which each
loop will
loop return to the beginning of the
loop (that is, the current play time gets reset to audiobuffersourcenode.
loopstart).
... this property is only used if the
loop property is true.
...And 21 more matches
Bytecode Descriptions
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.
...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 17 more matches
Drawing graphics - Learn web development
loops and animations we have so far covered some very basic uses of 2d canvas, but really you won't experience the full power of canvas unless you update or animate it in some way.
... creating a
loop playing with
loops in canvas is rather fun — you can run canvas commands inside a for (or other type of)
loop just like any other javascript code.
... math.floor(math.random() * (max-min+1)) + (min); } let length = 250; let moveoffset = 20; for(var i = 0; i < length; i++) { } here we are implementing the same degtorad() function we saw in the triangle example above, a rand() function that returns a random number between given lower and upper bounds, length and moveoffset variables (which we'll find out more about later), and an empty for
loop.
...And 12 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
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.
...And 12 more matches
Arrays - Learn web development
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.
...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.
...And 10 more matches
for - JavaScript
the for statement creates a
loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the
loop.
... syntax for ([initialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the
loop begins.
...variables declared with var are not local to the
loop, i.e.
...And 9 more matches
HTML parser threading
these two methods along with timerflush (discussed later) are the entry points from the parser thread event
loop into nshtml5streamparser.
...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).
...And 8 more matches
Background Tasks API - Web APIs
concepts and usage the main thread of a web browser is centered around its event
loop.
...in addition, the event
loop handles interactions with the operating system, updates to the browser's own user interface, and so forth.
... 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.
...And 8 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.
... 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.
...And 8 more matches
JavaScript Daemons Management - Archive of obsolete content
"start" : "syncstart"](!this.backw); }; /* settings tools */ daemon.prototype.make
loop = function () { this.reversals = infinity; }; daemon.prototype.unmake
loop = function () { this.reversals = 0; }; daemon.prototype.setrate = function (vto) { var nrate = number(vto); if (!isfinite(nrate) || nrate < 1) { return; } this.rate = nrate; this.synchronize(); }; daemon.prototype.forceposition = function (vto) { if (isfinite(vto)) { this.index = m...
...ength - this.index, breverse, bforce); }; daemon.prototype.reclose = function (bforce) { /* warning: this method requires the daemon.prototype.makesteps() and daemon.prototype.close() methods */ return this.close(this.isatend() !== this.backw, bforce || false); }; /* others */ daemon.prototype.restart = function () { this.stop(); this.start(); }; daemon.prototype.
loopuntil = function (vdate) { if (!isfinite(this.length)) { return; } var ntime = vdate.constructor === date ?
...set it to infinity for a “
loop mode”.
...And 7 more matches
A first splash into JavaScript - Learn web development
note: many of the code features you'll see in javascript are the same as in other programming languages — functions,
loops, etc.
...we select all paragraphs inside <div class="resultparas"></div>, then
loop through each one, setting their textcontent to '' (an empty string).
...
loops one part of the above code that we need to take a more detailed look at is the for
loop.
...And 7 more matches
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
loop: a boolean indicating whether the audio should play in a
loop.
...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.
...And 7 more matches
Using the Gamepad API - Web APIs
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.
...when one is connected, we grab the gamepad using navigator.getgamepads()[0], print information about the gamepad into our gamepad info div, and fire the game
loop() function that starts the whole ball movement process up.
...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.
...And 7 more matches
Implementing controls using the Gamepad API - Game development
update() is executed on every frame inside the game
loop, to update the actual status of the gamepad object regularly: update: 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].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.cont...
...then it
loops through buttons and axes to get their actual states and values.
...And 6 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
objective: to understand asynchronous
loops and intervals and what they are useful for.
...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.
... you probably want to create a variable that starts at 0, then increments by one every second using a constant
loop.
...And 6 more matches
for...of - JavaScript
the for...of statement creates a
loop iterating over iterable objects, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined iterables.
...like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.iterator] const articleparagraphs = document.queryselectorall('article > 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.
... 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.
...And 6 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.
... objective: to test comprehension of javascript
loops, functions, conditionals, and events.
... 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.
...And 5 more matches
Object building practice - Learn web development
e = random(10,20); let ball = new ball( // ball position always drawn at least one ball width // away from the edge of the canvas, to avoid drawing errors random(0 + size,width - size), random(0 + size,height - size), random(-7,7), random(-7,7), 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')', size ); balls.push(ball); } the while
loop creates a new instance of our ball() using random values generated with our random() function, then push()es it onto the end of our balls array, but only while the number of balls in the array is less than 25.
... add the following to the bottom of your code now: function
loop() { ctx.fillstyle = 'rgba(0, 0, 0, 0.25)'; ctx.fillrect(0, 0, width, height); for (let i = 0; i < balls.length; i++) { balls[i].draw(); balls[i].update(); } requestanimationframe(
loop); } all programs that animate things generally involve an animation
loop, which serves to update the information in the program and then render the resulting view on each frame of the animation; this is the basis for most games and oth...
...our
loop() function does the following: sets the canvas fill color to semi-transparent black, then draws a rectangle of the color across the whole width and height of the canvas, using fillrect() (the four parameters provide a start coordinate, and a width and height for the rectangle drawn).
...And 5 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
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.
...And 5 more matches
for await...of - JavaScript
the for await...of statement creates a
loop iterating over async iterable objects as well as on sync iterables, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined async/sync iterables.
...< 3) { return promise.resolve({ value: this.i++, done: false }); } return promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asynciterable) { console.log(num); } })(); // 0 // 1 // 2 iterating over async generators since the return values of async generators conform to the async iterable protocol, they can be
looped using for await...of.
... let responsesize = 0; // the for-await-of
loop.
...And 5 more matches
while - JavaScript
the while statement creates a
loop that executes a specified statement as long as the test condition evaluates to true.
... syntax while (condition) statement condition an expression evaluated before each pass through the
loop.
...when condition evaluates to false, execution continues with the statement after the while
loop.
...And 5 more matches
Index - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Redirections in HTTP - HTTP
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.
... 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.
...And 4 more matches
for...in - JavaScript
description a for...in
loop only iterates over enumerable, non-symbol properties.
...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).
...And 4 more matches
label - JavaScript
note: labeled
loops or blocks are very uncommon.
... usually function calls can be used instead of
loop jumps.
...break can be used with any labeled statement, and continue can be used with
looping labeled statements.
...And 4 more matches
Desktop gamepad controls - Game development
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; } } 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.
...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
OS.File for the main thread
let writestream = function writestream(data, outfile, chunksize) { let view = new uint8array(data); let
loop = function
loop(pos) { // define a recursive asynchronous
loop.
... 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 3 more matches
AsyncTestUtils extended framework
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.
... 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.
...And 3 more matches
nsIAppShell
nt, in voidptrref aevent); obsolete since gecko 1.9 void listentoeventqueue(in nsieventqueue aqueue, in prbool alisten); obsolete since gecko 1.9 void resumenative(); void run(); void runinstablestate(in nsirunnable arunnable); void spindown(); obsolete since gecko 1.9 void spinup(); obsolete since gecko 1.9 void suspendnative(); attributes attribute type description event
loopnestinglevel unsigned long the current event
loop nesting level.
... exit() exit the handle event
loop.
...run() enter an event
loop.
...And 3 more matches
nsIWebBrowserChrome
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.
...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.
...And 3 more matches
break - JavaScript
the break statement terminates the current
loop, switch, or label statement and transfers program control to the statement following the terminated statement.
...if the statement is not a
loop or switch, this is required.
...the labeled statement can be any block statement; it does not have to be preceded by a
loop statement.
...And 3 more matches
Building up a basic demo with Babylon.js - Game development
creating a rendering
loop to make the scene actually visible we have to render it.
... 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.
...to show actual animation, we need to make changes to these values inside the rendering
loop at the end of our code, so they are updated on every frame.
...And 2 more matches
Audio for Web games - Game development
one way you can make your music soundtrack more dynamic is by splitting it up into component
loops or 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.
... either way you may want to synchronize tracks or
loops.
...And 2 more matches
Build the brick field - Game development
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.
...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.
... brick drawing logic now let's create a function to
loop through all the bricks in the array and draw them on the screen.
...And 2 more matches
Build the brick field - Game development
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.
... 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.
...And 2 more matches
JavaScript building blocks - Learn web development
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.
...
looping code sometimes you need a task done more than once in a row.
...in programming,
loops perform this job very well.
...And 2 more matches
Rendering a list of Vue components - Learn web development
in this 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.
... objective: to learn how to
loop through an array of data and render it in multiple components.
...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.
...And 2 more matches
HTTP Cache
also memory pool management, eviction, visiting
loops happen on this thread.
...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.
... == 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...
...And 2 more matches
How to embed the JavaScript engine
jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event
loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; ...
... jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event
loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr, js::fireonnewglobalhook)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *file...
... jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event
loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr, js::fireonnewglobalhook)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *file...
...And 2 more matches
Plug-in Basics - Plugins
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.
... 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.
...And 2 more matches
Using images - Web APIs
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.
...And 2 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
when the instrument plays, it will move across this set of beats and
loop the bar.
...e another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to take an array of files and
loop over them to load more than one sample.
... 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.
...And 2 more matches
Functions - JavaScript
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...
...And 2 more matches
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.
... 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.
...And 2 more matches
do...while - JavaScript
the do...while statement creates a
loop that executes a specified statement until the test condition evaluates to false.
...to execute multiple statements within the
loop, use a block statement ({ ...
... condition an expression evaluated after each pass through the
loop.
...And 2 more matches
Statements and declarations - JavaScript
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.
... iterations do...while creates a
loop that executes a specified statement until the test condition evaluates to false.
...And 2 more matches
for each...in - Archive of obsolete content
please see warning: javascript 1.6's for-each-in
loops are deprecated for migration help.
...this variable is local to the function, not to the
loop.
...to execute multiple statements within the
loop, use a block statement ({ ...
... examples using for each...in warning: never use a
loop like this on arrays.
Index - Game development
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.
...we touch on css transitions and css animations, and javascript
loops involving window.requestanimationframe.
...let's explore how to create a group of bricks and print them on screen using a
loop.
... 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.
Third-party APIs - Learn web development
eadline.main; } clearfix.setattribute('class','clearfix'); article.appendchild(heading); heading.appendchild(link); article.appendchild(img); article.appendchild(para1); article.appendchild(para2); article.appendchild(clearfix); section.appendchild(article); } } } there's a lot of code here; let's explain it step by step: the while
loop is a common pattern used to delete all of the contents of a dom element, in this case, the <section> element.
...the
loop ends when <section> no longer has any children.
...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>.
Basic math in JavaScript — numbers and operators - Learn web development
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.
...we'll look at
loops in detail later on in the course.
Adding features to our bouncing balls demo - Learn web development
to do this, you need to make some changes to the
loop() function.
...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.
Multimedia: video - Learn web development
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.
... <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.
Dynamic behavior in Svelte: working with variables and props - Learn web development
html doesn't have a way of expressing logic — like conditionals and
loops.
...{/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.
... now we just need to use the helper function in the {#each}
loop; update it like this: ...
...so whenever filter or todos changes, the filtertodos() function will be re-evaluated and the items inside the
loop will be updated.
Profiling with the Firefox Profiler
tracing markers red: these indicate that the event
loop is being unresponsive.
... 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.
...if you notice these things happening in a
loop, that's a bug to be fixed, since we're likely "layout thrashing".
... because of the non-zero overhead of the instrumentation, the sample label shouldn't be placed inside hot
loops.
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...
... * generate a random value to use as iv for aes cbc * open an input file and an output file, * wrap the symmetric and mac keys using public key * write a header to the output that identifies the two wrapped keys * and public key *
loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; seckeypublickey ...
...!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...
...se 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 (slot) { pk...
Index
the properties each op adds to the properties vector are added to the set of values the for-in
loop will iterate over.
...(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.
... 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.
...(this differs from longstanding for..in
loop order, which uses the order in which obj's properties were defined.
Tracing JIT
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.
... 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 compiled fragment of code returned to the monitor on successful
loop-close is called a trace.
AudioBufferSourceNode - Web APIs
audiobuffersourcenode.
loop a boolean attribute indicating if the audio asset must be replayed when the end of the audiobuffer is reached.
... audiobuffersourcenode.
loopstart optional a floating-point value indicating the time, in seconds, at which playback of the audiobuffer must begin when
loop is true.
... its default value is 0 (meaning that at the beginning of each
loop, playback begins at the start of the audio buffer).
... audiobuffersourcenode.
loopend optional a floating-point number indicating the time, in seconds, at which playback of the audiobuffer stops and
loops back to the time indicated by
loopstart, if
loop is true.
Rendering and the WebXR frame animation callback - Web APIs
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.
... note that this code doesn't have a
loop!
... when a frame is dropped, the contents of the affected display area simply don't change for that pass through the frame
loop.
... 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.
Using the Web Animations API - Web APIs
: #alice { animation: alicetumbling infinite 3s linear; } @keyframes alicetumbling { 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.
...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.
...that’s impossible to do with css without recalculating durations in every css rule, but with the web animations api, we could use the document.getanimations() method to
loop over each animation on the page and halve their playbackrates, like so: document.getanimations().foreach( function (animation) { animation.updateplaybackrate(animation.playbackrate * .5); } ); with the web animations api, all you need to change is just one little property!
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 ...
... var slicewidth = width * 1.0 / bufferlength; var x = 0; now we run through a
loop, defining the position of a small segment of the wave for each point in the buffer at a certain height based on the data point value form the array, then moving the line across to the place where the next wave segment should be drawn: for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.movet...
... 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.
... 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.
Closures - JavaScript
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.
...the
loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.
...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).
...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.
Indexed collections - JavaScript
a for...in
loop will not find any property on the array.
...false in a boolean context—if your array consists only of dom nodes, for example—you can use a more efficient idiom: let divs = document.getelementsbytagname('div') for (let i = 0, div; div = divs[i]; i++) { /* process div in some way */ } this avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the
loop for added convenience.
...unassigned values are not iterated in a foreach
loop.
...irst // second // fourth if (array[2] === undefined) { console.log('array[2] is undefined') // true } array = ['first', 'second', undefined, 'fourth'] array.foreach(function(element) { console.log(element) }) // first // second // undefined // fourth since javascript elements are saved as standard object properties, it is not advisable to iterate through javascript arrays using for...in
loops, because normal elements and all enumerable properties will be listed.
Iterators and generators - JavaScript
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.
... 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.
...for example: the for-of
loops, yield*.
InternalError: too much recursion - JavaScript
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).
... 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.
... function
loop(x) { // the base case is missing
loop(x + 1); // recursive call }
loop(0); // internalerror: too much recursion class error: too much recursion class person{ constructor(){} set name(name){ this.name = name; // recursive call } } const tony = new person(); tony.name = "tonisha"; // internalerror: too much recursion when a value is assigned to the property name (this.name = name;) javascript needs to set that property.
Iteration protocols - JavaScript
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.
... 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.
... ]).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...
...this makes multiple // iterations over the iterable safe for non-trivial cases, // such as use of break or nested
looping over the same iterable.
Optimizing startup performance - Web Performance
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.
...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.
...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.
2D maze game with device orientation - Game development
after leveldata, but still in the initlevels function, we're adding the blocks into an array in the for
loop using some of the framework-specific methods: for(var i=0; i<this.maxlevels; i++) { var newlevel = this.add.group(); newlevel.enablebody = true; newlevel.physicsbodytype = phaser.physics.arcade; for(var e=0; e<this.leveldata[i].length; e++) { var item = this.leveldata[i][e]; newlevel.create(item.x, item.y, 'element-'+item.t); } newlevel.setall('body.immova...
...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.
...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.
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and
loops.
...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.
...the function could also include a
loop, which iterates through all of the fields in the form, checking each one in turn.
Practical positioning examples - Learn web development
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.
... in the settabhandler() function, the tab has an onclick event handler set 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 for
loop is used to cycle through all the panels and remove any classes that are present on them.
Functions — reusable blocks of code - Learn web development
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.
...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.
... note: the same scoping rules do not apply to
loop (e.g.
Server-side web frameworks - Learn web development
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.
... 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.
...deno aims to fill in some of the
loop-holes in node.js by providing a mechanism that naturally maintains better security.
Handling common JavaScript problems - Learn web development
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.
...see good-for-
loop.html (see the source code also) for a version that works.
PR_InitializeNetAddr
this must be pr_ipaddrnull, pr_ipaddrany, or pr_ipaddr
loopback.
... 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.
... pr_ipaddr
loopback assign logical pr_inaddr_
loopback.
Index
when used with
looping mode, the different connections are separated with horizontal lines.
... -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete.
...to make the tool continue to accept connections, switch on
looping mode with the -l option.
NSS tools : ssltab
when used with
looping mode, the different connections are separated with horizontal lines.
...-l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete.
...to make the tool continue to accept connections, switch on
looping mode with the -l option.
NSS tools : ssltap
when used with
looping mode, the different connections are separated with horizontal lines.
...-l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete.
...to make the tool continue to accept connections, switch on
looping mode with the -l option.
NSS Tools ssltap
when used with
looping mode, the different connections are separated with horizontal lines.
... -l turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete.
...to make the tool continue to accept connections, switch on
looping mode with the -l option.
NSS tools : ssltap
when used with
looping mode, the different connections are separated with horizontal lines.
... -l prefix turn on
looping; that is, continue to accept connections rather than stopping after the first connection is complete.
...to make the tool continue to accept connections, switch on
looping mode with the -l option.
SpiderMonkey Internals
common cases are inlined in the interpreter
loop, breaking any abstractions that stand in the way.
...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.
...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 ...
JSNewEnumerateOp
the properties each op adds to the properties vector are added to the set of values the for-in
loop will iterate over.
... an object is "enumerated" when it's the target of a for-in
loop or js_enumerate.
... the callback's job is to populate properties with all property keys that the for-in
loop should visit.
JS_Enumerate
(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.
...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.
...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.
Index
this method is generally called within a
loop to iterate over the elements in the enumerator.
...this method is generally called within a
loop to iterate over the strings in the enumerator.
...this method is generally called within a
loop to iterate over the strings in the enumerator.
imgIContainer
loopcount long number of times to
loop the image.
... 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.
nsIServerSocket
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 init( in long aport, in boolean a
loopbackonly, in long abacklog ); parameters aport the port of the server socket.
... a
loopbackonly if true, the server socket will only respond to connections on the local
loopback interface.
BaseAudioContext.createDelay() - Web APIs
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 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'); } ...
Applying styles and colors - Web APIs
// 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.
...every step in the for
loop draws a set of circles with an increasing radius.
... screenshotlive sample patterns in one of the examples on the previous page, we used a series of
loops to create a pattern of images.
Basic animations - Web APIs
for instance, it isn't possible to do an animation from within a for
loop.
...for more information about the animation
loop, especially for games, see the article anatomy of a video game in our game development zone.
... 0, 0, 0)'; ctx.arc(0, 0, 3, 0, math.pi * 2, true); ctx.fill(); ctx.restore(); ctx.beginpath(); ctx.linewidth = 14; ctx.strokestyle = '#325fa2'; ctx.arc(0, 0, 142, 0, math.pi * 2, true); ctx.stroke(); ctx.restore(); window.requestanimationframe(clock); } window.requestanimationframe(clock); <canvas id="canvas" width="150" height="150"></canvas> screenshotlive sample a
looping panorama in this example, a panorama is scrolled left-to-right.
Transformations - Web APIs
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.
... 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.
DelayNode.delayTime - Web APIs
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 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'); } ...
DelayNode - Web APIs
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 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'); } ...
EventTarget.addEventListener() - Web APIs
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.
...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.
...moreover, in the first case, it is not possible to call removeeventlistener() because no reference to the anonymous function is kept (or here, not kept to any of the multiple anonymous functions the
loop might create.) in the second case, it's possible to do myelement.removeeventlistener("click", processevent, false) because processevent is the function reference.
HTMLMarqueeElement - Web APIs
htmlmarqueeelement.
loop sets the number of times the marquee will scroll.
... 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.
Using IndexedDB - Web APIs
transactions are tied very closely to the event
loop.
... if you make a transaction and return to the event
loop without using it then the transaction will become inactive.
...if you return to the event
loop without extending the transaction then it will become inactive, and so on.
PaymentResponse.retry() - Web APIs
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.
Raining rectangles - Web APIs
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.
WebXR performance guide - Web APIs
talk about general stuff like limiting how many different
loops there are during rendering, avoiding unnecessary drawing, etc.
...that means that for every frame, the javascript runtime has to allocate memory for those and set them up—possibly triggering garbage collection—and then when each interaction of the
loop is completed, the memory is released.
... } } now, instead of allocating variables every
loop iteration, we're using global constants(or class member constants).
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 = true; note, the
loopstart and
loopend attributes are not supported in webkitaudiocontext.
window.requestIdleCallback() - Web APIs
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.
... 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.
... parameters callback a reference to a function that should be called in the near future, when the event
loop is idle.
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.
...enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event
loop.
XRSession.requestAnimationFrame() - Web APIs
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.
... // begin the session’s animation
loop.
HTTP Index - HTTP
it is used for tracking message forwards, avoiding request
loops, and identifying the protocol capabilities of senders along the request/response chain.
... 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.
... 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.
Array.prototype.forEach() - JavaScript
(however, callback may do so) there is no way to stop or break a foreach()
loop other than by throwing an exception.
... 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.
... converting a for
loop to foreach const items = ['item1', 'item2', 'item3'] const copyitems = [] // before for (let i = 0; i < items.length; i++) { copyitems.push(items[i]) } // after items.foreach(function(item){ copyitems.push(item) }) printing the contents of an array note: in order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the arra...
Function.prototype.apply() - JavaScript
write a
loop?
... 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.
...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.
Object.entries() - JavaScript
the object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in
loop.
... (the only important difference is that a for...in
loop enumerates properties in the prototype chain as well).
...the ordering of the properties is the same as that given by
looping over the property values of the object manually.
Object.values() - JavaScript
the object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in
loop.
... (the only difference is that a for...in
loop enumerates properties in the prototype chain as well.) the source for this interactive example is stored in a github repository.
...the ordering of the properties is the same as that given by
looping over the property values of the object manually.
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 current iteration and returning a variable to represent the // individual character console.log(chr); } function getwholechar(str, i) { var code = str.charcodeat(i); if (number.isnan(code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { return str.charat(i); } // high surrogate (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 <= code && code <= 0xdbff) { if (str.length <= (i + 1)) { throw 'high surr...
... let str = 'a\ud87e\udc04z' // we could also use a non-bmp character directly for (let i = 0, chr; i < str.length; i++) { [chr, i] = getwholecharandi(str, i) // adapt this line at the top of each
loop, passing in the whole string and // the current iteration and returning an array with the individual character // and 'i' value (only changed if a surrogate pair) console.log(chr) } function getwholecharandi(str, i) { let code = str.charcodeat(i) if (number.isnan(code)) { return '' // position not found } if (code < 0xd800 || code > 0xdfff) { return [str.charat(i), i] /...
lang/functional - Archive of obsolete content
calling the wrapped version will call the original function during the next event
loop.
... 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.
Using Dependent Libraries In Extension Components - Archive of obsolete content
to find // <extensiondir>/libraries nscomptr<nsifile> libraries; rv = alocation->getparent(getter_addrefs(libraries)); if (ns_failed(rv)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return ns_error_unexpected; library->setnativeleafname(ns_literal_cstring("libraries")); library->appendnative(ns_literal_cstring("dummy")); //
loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); prlibrary *lib; library->load(&lib); // 1) we don't care if this failed!
... // <extensiondir>/libraries nscomptr<nsifile> libraries; rv = alocation->getparent(getter_addrefs(libraries)); if (ns_failed(rv)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return ns_error_unexpected; library->setnativeleafname(ns_literal_cstring("libraries")); library->appendnative(ns_literal_cstring("dummy")); nscstring path; //
loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); rv = library->getnativepath(path); if (ns_failed(rv)) return rv; //at this point, we would have used prlibrary *lib; library->load(&lib); //but we can't use that in os x.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
// 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...
...// 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; } } // 5) set user preferences //browser lockpref("browser.startup.homepage", "http://www.int-evry.fr/s2ia/por...
Nanojit - Archive of obsolete content
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.
... 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.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
overview 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.
... the use of the xt main
loop has been a problem for modern plugin development because very few modern applications that want to take advantage of the capabilities of newer toolkits use xt.
Old Proxy API - Archive of obsolete content
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.
... return "something"; } }); var q = p.azerty; // infinite
loop the receiver argument in 'get' and 'set' traps may not be the proxy itself: var proxy; var handler = { has: function (name) { return name == 'foo'; }, get: function (rcvr, name) { if (name != 'foo') return undefined; print(proxy !== rcvr); return "bye"; }, }; proxy = proxy.create(handler); var c = object.create(proxy); print(c.f...
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 ...
...the comment nodes are
looped over with data output using the simplified e4x syntax.
Reference - Archive of obsolete content
the for each...in
loop should either be listed on this page or moved to a different category.
...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.
Building up a basic demo with the PlayCanvas engine - Game development
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.
...to show actual animation, we need to make changes to these values inside the rendering
loop, so they are updated on every frame.
Building up a basic demo with Three.js - Game development
right after the function declaration, we're invoking it for the first time to start the
loop, after which it will be used indefinitely.
...to show animation, we need to make changes to these values inside the render
loop, so they update on each frame.
Collision detection - Game development
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.
Finishing up - Game development
; and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to call itself over and over again: requestanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe()
loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser.
...this produces a more efficient, smoother animation
loop than the older setinterval() method.
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
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).
... /* 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.
Video and audio content - Learn web development
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.
...
loop makes the video (or audio) start playing again whenever it finishes.
Introducing asynchronous JavaScript - Learn web development
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.
Client-side storage - Learn web development
this
loops through the different video names, trying to load a record identified by each name from the videos database.
... function init() { //
loop through the video names one by one for(let i = 0; i < videos.length; i++) { // open transaction, get object store, and get() each video by name let objectstore = db.transaction('videos_os').objectstore('videos_os'); let request = objectstore.get(videos[i].name); request.onsuccess = function() { // if the result exists in the database (is not undefined) if(request.res...
Useful string methods - Learn web development
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.
Inheritance in JavaScript - Learn web development
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()!
... ultimately, objects are just another form of code reuse, like functions or
loops, with their own specific roles and advantages.
Working with JSON - Learn web development
next, we use a for
loop to
loop through each object in the array.
... 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().
Getting started with Svelte - Learn web development
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.
... 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.
Understanding client-side JavaScript frameworks - Learn web development
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.
...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.
Gecko Logging
example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int start = time::nowms(); moz_log(slogger, loglevel::debug, ("starting
loop.")); while (i++ < 10) { moz_log(slogger, loglevel::verbose, ("i = %d", i)); } // only calculate the elapsed time if the warning level is enabled.
... if (moz_log_test(slogger, loglevel::warning)) { int elapsed = time::nowms() - start; if (elapsed > 1000) { moz_log(slogger, loglevel::warning, ("
loop took %dms!", elapsed)); } } if (i != 10) { moz_log(slogger, loglevel::error, ("i should be 10!")); } } enabling logging the log level for a module is controlled by setting an environment variable before launching the application.
Performance best practices for Firefox front-end engineers
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.
...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.
DeferredTask.jsm
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.
Gecko Profiler FAQ
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!
...it runs a
loop that works like this: iterate over all threads.
PRNetAddr
(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.
PRSockOption
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_mcast
loopback ip multicast
loopback.
PRSocketOptionData
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_
loopback ip multicast
loopback.
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...
... *
loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc ...
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...
... *
loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc ...
Encrypt Decrypt_MAC_Using Token
*
loop until eof(input): * read a buffer of ciphertext from input file.
... *
loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc ...
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...
... *
loop until eof(input) * read a buffer of plaintext from input file * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv * store the last block of ciphertext as the new iv * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *...
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...
...*
loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsi...
Exact Stack Rooting
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.
Invariants
(we can probably
loop forever if that happens.
...(a cycle would be very silly and could cause inf
loops.
JS_ThrowStopIteration
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 engine automatically catches the exception and exits the
loop.
Animated PNG graphics
4 num_plays unsigned int the number of times to
loop this apng.
... 0 indicates infinite
looping.
XPCOM array guide
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.
...comarray<nsielements>& elements) { printf("there are %d elements.\n", elements.count()); } // no const, so we can modify the array void tweakarray(nscomarray<nsielement>& elements, nsielement* newelement) { elements.removeobjectat(0); elements.appendobject(newelement); } in-place enumeration the callback-based enumeration in nscomarray<t> is about as fast as, if not faster than, standard
loop-based iteration.
nsIAppShellService
quit() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) exit the event
loop, shut down the app.
... 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.
nsIAppStartup
quit() exit the event
loop, and shut down the application.
... run() runs an application event
loop: normally the main event pump which defines the lifetime of the application.
WebIDL bindings
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.
... 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.
AudioProcessingEvent - Web APIs
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.
...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...
AudioScheduledSourceNode.onended - Web APIs
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.
BaseAudioContext.createScriptProcessor() - Web APIs
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.
...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
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.
...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...
Using files from web applications - Web APIs
} this
loop iterates over all the files in the file list.
... 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/").
FileList - Web APIs
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.
...> <!--multiple is set to allow multiple files to be selected--> <input id="myfiles" multiple type="file"> </body> <script> var pullfiles=function(){ // love the query selector var fileinput = document.queryselector("#myfiles"); var files = fileinput.files; // cache files.length var fl = files.length; var i = 0; while ( i < fl) { // localize file var in the
loop var file = files[i]; alert(file.name); i++; } } // set the input element onchange to call pullfiles document.queryselector("#myfiles").onchange=pullfiles; //a.t </script> </html> specifications specification status comment file apithe definition of 'filelist' in that specification.
Using the Frame Timing API - Web APIs
the performanceframetiming interface provides frame timing data about the browser's event
loop.
... a frame represents the amount of work a browser does in one event
loop iteration such as processing dom events, resizing, scrolling, rendering, css animations, etc.
Frame Timing API - Web APIs
the performanceframetiming interface provides frame timing data about the browser's event
loop.
... a frame represents the amount of work a browser does in one event
loop iteration such as processing dom events, resizing, scrolling, rendering, css animations, etc.
Gamepad.axes - Web APIs
syntax readonly attribute double[] axes; example function game
loop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; } else { var gp = navigator.getgamepads()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.top ...
...= b*2 + "px"; var start = raf(game
loop); }; value an array of double values.
Gamepad.buttons - Web APIs
function game
loop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { ...
... b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(game
loop); }; value an array of gamepadbutton objects.
GamepadButton - Web APIs
function game
loop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { ...
... b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(game
loop); }; specifications specification status comment gamepadthe definition of 'gamepadbutton' in that specification.
HTMLCanvasElement.getContext() - Web APIs
desynchronized: boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event
loop (gecko only) willreadfrequently: boolean that indicates whether or not a lot of read-back operations are planned.
... desynchronized: boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event
loop antialias: boolean that indicates whether or not to perform anti-aliasing.
NodeList - Web APIs
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.
... 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().
PerformanceFrameTiming - Web APIs
performanceframetiming is an abstract interface that provides frame timing data about the browser's event
loop.
... a frame represents the amount of work a browser does in one event
loop such as processing dom events, resizing, scrolling, rendering, css animations, etc..
ScriptProcessorNode.bufferSize - Web APIs
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.
...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
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.
...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
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.
...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...
SharedWorkerGlobalScope - Web APIs
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.
StyleSheetList - Web APIs
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.
Simple color animation - Web APIs
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).
... 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.
Animating textures in WebGL - Web APIs
getting access to the video the first step is to create the <video> element that we'll use to retrieve the video frames: // will set to true when video can be copied to texture var copyvideo = false; function setupvideo(url) { const video = document.createelement('video'); var playing = false; var timeupdate = false; video.autoplay = true; video.muted = true; video.
loop = true; // waiting for these 2 events ensures // there is data in the video video.addeventlistener('playing', function() { playing = true; checkready(); }, true); video.addeventlistener('timeupdate', function() { timeupdate = true; checkready(); }, true); video.src = url; video.play(); function checkready() { if (playing && timeupdate) { copyvi...
...we set it to autoplay, mute the sound, and
loop the video.
Movement, orientation, and motion: A WebXR example - Web APIs
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.
...the two lines of code that adjust the canvas size are not needed in regular webxr rendering
loops.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
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.
WorkerGlobalScope - Web APIs
each workerglobalscope has its own event
loop.
... deprecated methods workerglobalscope.close() discards any tasks queued in the workerglobalscope's event
loop, effectively closing this particular scope.
system - CSS: Cascading Style Sheets
once the end of the list of symbols is reached, it will
loop back to the beginning and start over.
...once the system has
looped through all the specified symbols, it will fall back.
Using CSS animations - CSS: Cascading Style Sheets
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.
... 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.
Using CSS transitions - CSS: Cascading Style Sheets
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.
Overview of events and handlers - Developer guides
with the change to dynamic page rendering, browsers
loop continuously between processing, drawing, presenting content, and waiting for some new event trigger.
...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.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
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.
...
loop a boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio.
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
loop this attribute indicates the number of times a sound is to be played and either has a numeric value or the keyword infinite.
... 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.
<input type="file"> - HTML: Hypertext Markup Language
input.addeventlistener('change', updateimagedisplay); whenever the updateimagedisplay() function is invoked, we: use a while
loop to empty the previous contents of the preview <div>.
... if files have been selected, we
loop through each one, printing information about it into the preview <div>.
<video>: The Video Embed element - HTML: Hypertext Markup Language
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.
...explainer, examples
loop a boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video.
Using Promises - JavaScript
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.
...) */ timing to avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise: promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later when the queue is emptied at the end of the current run of the javascript event
loop, i.e.
JavaScript error reference - JavaScript
use //# insteadsyntaxerror: a declaration in the head of a for-of
loop can't have an initializersyntaxerror: applying the "delete" operator to an unqualified name is deprecatedsyntaxerror: for-in
loop head declarations may not have initializerssyntaxerror: function statement requires a namesyntaxerror: identifier starts immediately after numeric literalsyntaxerror: illegal charactersyntaxerror: invalid regular expression flag "x"syntaxerror: missing ) after argument...
...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[@@iterator]() - JavaScript
examples iteration using for...of
loop html <ul id="letterresult"> </ul> javascript var arr = ['a', 'b', 'c']; var earr = arr[symbol.iterator](); var letterresult = document.getelementbyid('letterresult'); // your browser must support for..of
loop // and let-scoped variables in for
loops // const and var could also be used for (let letter of earr) { letterresult.innerhtml += "<li>" + letter + "</li>"; } result alternative it...
... function logiterable(it) { if (!(symbol.iterator in object.getprototypeof(it) /* or "symbol.iterator in object.__proto__" or "it[symbol.iterator]" */)) { console.log(it, ' is not an iterable object...'); return; } var iterator = it[symbol.iterator](); // your browser must support for..of
loop // and let-scoped variables in for
loops // const and var could also be used for (let letter of iterator) { console.log(letter); } } // array logiterable(['a', 'b', 'c']); // a // b // c // string logiterable('abc'); // a // b // c logiterable(123); // 123 " is not an iterable object..." specifications specification ecmascript (ecma-262)the definition of '...
Array.prototype.every() - JavaScript
// --------------- // modifying items // --------------- let arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr[index+1] -= 1 console.log(`[${arr}][${index}] -> ${elem}`) return elem < 2 }) //
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 runs for 2 iterations only, as the remaining // items are `pop()`ed off // // 1st iteration: [1,2,3][0] -> 1 // 2nd iteration: [1,2][1] -> 2 specifications specification ecmascript (ecma-262)the definition of 'array.prototype.every' in that specification.
Array.prototype.values() - JavaScript
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].
...or.next().value; // undefined one-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } // undefined reason: when next().done=true or currentindex>length the for..of
loop ends.
Map - JavaScript
description a map object iterates its elements in insertion order — a for...of
loop returns an array of [key, value] for each iteration.
...even though every nan is not equal to itself (nan !== nan is true), the following example works because nans are indistinguishable from each other: let mymap = new map() mymap.set(nan, 'not a number') mymap.get(nan) // "not a number" let othernan = number('foo') mymap.get(othernan) // "not a number" iterating map with for..of maps can be iterated using a for..of
loop: let mymap = new map() mymap.set(0, 'zero') mymap.set(1, 'one') for (let [key, value] of mymap) { console.log(key + ' = ' + value) } // 0 = zero // 1 = one for (let key of mymap.keys()) { console.log(key) } // 0 // 1 for (let value of mymap.values()) { console.log(value) } // zero // one for (let [key, value] of mymap.entries()) { console.log(key + ' = ' + value) } // 0 = zero // 1 =...
Object.defineProperty() - JavaScript
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.
...for non-symbols properties it also defines whether it shows up in a for...in
loop and object.keys() or not.
Object.getOwnPropertyNames() - JavaScript
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.
...(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in
loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with hasownproperty()).
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 ordering of the properties is the same as that given by
looping over the properties of the object manually.
RegExp.prototype.exec() - JavaScript
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.
String.prototype.charCodeAt() - JavaScript
'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.
...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
examples regexp.exec() and matchall() prior to the addition of matchall to javascript, it was possible to use calls to regexp.exec (and regexes with the /g flag) in a
loop to obtain all the matches: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while ((match = regexp.exec(str)) !== null) { console.log(`found ${match[0]} start=${match.index} end=${regexp.lastindex}.`); // expected output: "found football start=6 end=14." // expected output: "found foosball start=16 end=24." } with matchall available, you can avoi...
...d the while
loop and exec with g.
Comma operator (,) - JavaScript
this is commonly used to provide multiple parameters to a for
loop.
...the most common usage of this operator is to supply multiple parameters in a for
loop.
empty - JavaScript
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.
JavaScript
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.
... concurrency model and event
loop javascript has a concurrency model based on an "event
loop".
SVG animation with SMIL - SVG: Scalable Vector Graphics
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.
Fills and Strokes - SVG: Scalable Vector Graphics
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.
Delayed Execution - Archive of obsolete content
queuing a task in the main event
loop when a task needs to be only briefly delayed, such that it runs after the current call chain returns, it can be added directly to the main thread's event queue rather than scheduled as a timeout: function executesoon(func) { services.tm.mainthread.dispatch(func, ci.nsithread.dispatch_normal); } using nsitimers to schedule tasks in instances where settimeout() and setinterval() are unavailable, or insufficient, tasks can be scheduled with delays using nsitimer instances.
xml:base support in old browsers - Archive of obsolete content
// var ns = 'http://www.w3.org/xml/1998/namespace'; var att, protocolpos; var xmlbase = ''; var abs = false; // avoid
loop if node is not present if (!thisitem || !thisitem.nodename) { return xmlbase; } // check present element and higher up for xml:base // now check for the next matching local name up in the hierarchy (until the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { att = thisitem.getattribute('xml:base'); // xml: namespaces must use 'xml' ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
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).
DOMSubtreeModified - Archive of obsolete content
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).
Index - Archive of obsolete content
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.
MMgc - Archive of obsolete content
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.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
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.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
ew file(file, "components"); } } return file; } public file[] getfiles(string aprop) { file[] files = null; if (aprop.equals("apluginsdl")) { files = new file[1]; files[0] = new file(libxulpath, "plugins"); } return files; } } calling xpcom ui from another thread appstartup.run() enters the main event
loop and will stay there until the application exits.
Tuning Pageload - Archive of obsolete content
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.
Manipulating Lists - Archive of obsolete content
while (count--){ var item = list.selecteditems[0]; list.removeitemat(list.getindexofitem(item)); } } </script> <button label="delete" oncommand="deleteselection();"/> <listbox id="thelist" seltype="multiple"> <listitem label="cheddar"/> <listitem label="cheshire"/> <listitem label="edam"/> <listitem label="gouda"/> <listitem label="havartie"/> </listbox> inside the while
loop we first get the selecteditem at index 0.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
nsimodule* *aresult) { nsresult rv; nscomptr<nsifile> libraries; rv = alocation->getparent(getter_addrefs(libraries)); if (ns_failed(rv)) return rv; nscomptr<nsilocalfile> library(do_queryinterface(libraries)); if (!library) return ns_error_unexpected; library->setnativeleafname(ns_literal_cstring("libraries")); library->appendnative(ns_literal_cstring("dummy")); //
loop through and load dependent libraries for (char const *const *dependent = kdependentlibraries; *dependent; ++dependent) { library->setnativeleafname(nsdependentcstring(*dependent)); prlibrary *lib; library->load(&lib); // 1) we don't care if this failed!
2006-10-27 - Archive of obsolete content
he recommends that a non-xpcshell environment is needed really badly, but the big issue is that the xpcshell doesn't have an event
loop, so nothing asynchronous can be tested.
Plugins - Archive of obsolete content
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.
Generator comprehensions - Archive of obsolete content
console.log(it2.next()); // the second value from it, doubled when a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted: var result = dosomething(for (i in it) i * 2); the significant difference between the two examples being that by using the generator comprehension, you would only have to
loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.
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; ...
WebVR — Virtual Reality for the Web - Game development
r i = 0; i < devices.length; ++i) { if (devices[i] instanceof hmdvrdevice) { ghmd = devices[i]; break; } } if (ghmd) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { gpositionsensor = devices[i]; break; } } } }); this code will
loop through the available devices and assign proper sensors to the headsets — the first devices array contains the connected devices, and a check is done to find the hmdvrdevice, and assign it to the ghmd variable — using this you can set up the scene, getting the eye parameters, setting the field of view, etc.
Unconventional controls - Game development
we next add these lines after all the event listeners for keyboard and mouse, but before the draw method: var todegrees = 1 / (math.pi / 180); var horizontaldegree = 0; var verticaldegree = 0; var degreethreshold = 30; var grabstrength = 0; right after that we use the leap's
loop method to get the information held in the hand variable on every frame: leap.
loop({ hand: function(hand) { horizontaldegree = math.round(hand.roll() * todegrees); verticaldegree = math.round(hand.pitch() * todegrees); grabstrength = hand.grabstrength; output.innerhtml = 'leap motion: <br />' + ' roll: ' + horizontaldegree + '° <br />' ...
Move the ball - Game development
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.
Initialize the framework - Game development
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.
Win the game - Game development
unction: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } if (count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we
loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method.
Function - MDN Web Docs Glossary: Definitions of Web-related terms
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.
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
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.
Client-side form validation - Learn web development
// 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.
Build your own function - Learn web development
previous overview: building blocks next in this module making decisions in your code — conditionals
looping code functions — reusable blocks of code build your own function function return values introduction to events image gallery ...
Introduction to events - Learn web development
we then select all of them using document.queryselectorall(), then
loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when selected: const divs = document.queryselectorall('div'); for (let i = 0; i < divs.length; i++) { divs[i].onclick = function(e) { e.target.style.backgroundcolor = bgchange(); } } the output is as follows (try clicking around on it — have fun): most event handlers you...
Function return values - Learn web development
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.
Test your skills: JSON - Learn web development
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.
Routing in Ember - Learn web development
updating the todos display inside todolist one small final thing that we need to fix is that previously, inside todomvc/app/components/todo-list.hbs, we were accessing the todo-data service directly and
looping over all todos, as shown here: {{#each this.todos.all as |todo| }} since we now want to have our todolist component show a filtered list, we'll want to pass an argument to the todolist component representing the "current list of todos", as shown here: {{#each @todos as |todo| }} and that's it for this tutorial!
Mozilla’s UAAG evaluation report
(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.
Adding phishing protection data providers
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.
Benchmarking
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.
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...
mozbrowsererror
possible values are: fatal(crash) unknownprotocolfound filenotfound dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirect
loop unknownsockettype netreset notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfailure remotexul unsafecontenttype corruptedcontenterror certerror other example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsererror", function( event ) { console.log("an error occurred:" + event.detail);...
Embedding Tips
hint, add a native message processing
loop after the call to saveuri that terminates when onstatechange indicates persistence has finished..
How to Report a Hung Firefox
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.
JavaScript Tips
prefer to
loop through childnodes rather than using first/lastchild with next/previoussibling.
CustomizableUI.jsm
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.
JavaScript OS.Constants
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.
Task.jsm
we can easily
loop while // calling asynchronous functions, and wait multiple times.
MailNews automated testing
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.
I/O Functions
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.
PR_Wait
the boolean expression must be evaluated while in the monitor and within a
loop.
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
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.
NSS 3.44.1 release notes
new in nss 3.44.1 new functionality 1546229 - add ipsec ike support to softoken many new fips test cases (note: this has increased the source archive by approximately 50 megabytes for this release.) bugs fixed in nss 3.44.1 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) 1515236 - add a sslkeylogfile enable/disable flag at build.sh 1473806 - fix seckey_converttopublickey handling of non-rsa keys 1546477 - updates to testing for fips validation 1552208 - prohibit...
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 tech note4
critical : indicates whether the extension is critical value : the value of the extension
looping through all extensions certcertextension** extensions =cert->extensions; if (extensions) { while (*extensions) { secitem *ext_oid = &(*extensions)->id; secitem *ext_critical = &(*extensions)->critical; secitem *ext_value = &(*extensions)->value; /* id att...
NSS PKCS11 Functions
failing to terminate when the retry argument is pr_true can result in an endless
loop.
Python binding for 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.
pkfnc.html
failing to terminate when the retry argument is pr_true can result in an endless
loop.
NSS_3.12.3_release_notes.html
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.
Performance Hints
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!).
Hacking Tips
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.
JIT Optimization Strategies
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.
JSAPI Cookbook
the flag enumerable: true causes this property to be seen by for-in
loops.
JSAPI User Guide
*/ 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.
JSClass.flags
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.
JSConstDoubleSpec
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.
JSPropertyDescriptor
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.
JS_EnumerateStandardClasses
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.
JS_NewPropertyIterator
(this differs from longstanding for..in
loop order, which uses the order in which obj's properties were defined.
JS_ResolveStandardClass
the class's enumerate op should call js_enumeratestandardclasses(cx, obj), to define eagerly during for...in
loops any classes not yet resolved lazily.
JS_SetOptions
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.
JS_SetPropertyAttributes
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.
JS_SetPrototype
take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite
loop.
Shell global objects
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.
Finishing the Component
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.
Starting WebLock
* this method is generally called within a
loop to iterate over * the elements in the enumerator.
Mozilla internal string guide
*/ 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.
Components.classes
the properties of the components.classes object can be enumerated using a for...in
loop.
Components.interfaces
the properties of the components.interfaces object can be enumerated using a for...in
loop.
Components.results
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.
IAccessible2
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.
nsIDocShell
this method will post an event to complete the simulated load after returning to the event
loop.
nsIFaviconService
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.
nsIHttpChannel
if zero, the channel will fail to redirect and will generate a ns_error_redirect_
loop failure status.
nsISimpleEnumerator
this method is generally called within a
loop to iterate over the elements in the enumerator.
nsIStringEnumerator
this method is generally called within a
loop to iterate over the strings in the enumerator.
nsIUTF8StringEnumerator
this method is generally called within a
loop to iterate over the strings in 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
that is, ensures that it is visible and runs a local event
loop, exiting only once the window has been closed.
Reference Manual
p = p->next; } one often sees this pattern expressed as a for
loop, as well.
The libmime module
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.
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
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.
Initialization and Destruction - Plugins
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 ...
Debugger.Script - Firefox Developer Tools
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.
Waterfall - Firefox Developer Tools
for example, suppose we adapt the code above to make a timestamp every 10 iterations of the
loop, labeled with the iteration number: var iterations = 70; var multiplier = 1000000000; function calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { if (i % 10 == 0) { console.timestamp(i.tostring()); } var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(cand...
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
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.
AudioContext.getOutputTimestamp() - Web APIs
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.
AudioNode.connect() - Web APIs
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.
Beacon API - Web APIs
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.
BiquadFilterNode.getFrequencyResponse() - Web APIs
reate a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our biquad filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then
loop through each data set and output them in a human-readable list at the bottom of the page: var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; ...
Body.text() - Web APIs
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.
CSSStyleDeclaration.setProperty() - Web APIs
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.
CSSUnparsedValue.entries() - Web APIs
the cssunparsedvalue.entries() method 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 - Web APIs
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).
CSS Typed Object Model API - Web APIs
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).
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.fillStyle - Web APIs
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.
CanvasRenderingContext2D.strokeStyle - Web APIs
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.
Manipulating video using canvas - Web APIs
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.
DOMTokenList.entries() - Web APIs
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.
DataTransferItemList.DataTransferItem() - Web APIs
paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; //
loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { ...
DataTransferItemList.add() - Web APIs
paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; //
loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { ...
DataTransferItemList.clear() - Web APIs
paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; //
loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { ...
DataTransferItemList.length - Web APIs
paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; //
loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { ...
DataTransferItemList.remove() - Web APIs
paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; //
loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { ...
DedicatedWorkerGlobalScope.close() - Web APIs
the close() method of the dedicatedworkerglobalscope interface discards any tasks queued in the dedicatedworkerglobalscope's event
loop, effectively closing this particular scope.
DeprecationReportBody - Web APIs
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.
Document.querySelectorAll() - Web APIs
you can use any common
looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results.
EffectTiming.delay - Web APIs
examples in the pool of tears example, each tear is passed a random delay via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } //
loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); specifications specification statu...
EffectTiming.duration - Web APIs
examples in the pool of tears example, each tear is passed a random duration via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } //
loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); specifications specification sta...
EffectTiming.iterations - Web APIs
the default value is 1, indicating that it should only play once, but you can set it to any floating-point value (including positive infinity defaults to 1, and can also take a value of infinity to make it
loop infinitely.
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
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.
EventTarget.dispatchEvent() - Web APIs
notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event
loop, dispatchevent() invokes event handlers synchronously.
FormData.append() - Web APIs
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.
GlobalEventHandlers.onerror - Web APIs
<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.
msAudioCategory - Web APIs
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.
HTMLInputElement.multiple - Web APIs
example // fileinput is a <input type=file multiple> let fileinput = document.getelementbyid('myfileinput'); if (fileinput.multiple == true) { for (let i = 0; i < fileinput.files.length; i++) { //
loop fileinput.files } // only one file available } else { let file = fileinput.files.item(0); } ...
HTMLMediaElement - Web APIs
htmlmediaelement.
loop a boolean that reflects the
loop html attribute, which indicates whether the media element should start over when it reaches the end.
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
note that in each iteration of the
loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor.continue() - Web APIs
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.
IDBCursor.delete() - Web APIs
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.
IDBCursor.direction - Web APIs
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.
IDBCursor.key - Web APIs
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.
IDBCursor.primaryKey - Web APIs
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.
IDBCursor.source - Web APIs
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.
IDBCursor.update() - Web APIs
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.
IDBCursor - Web APIs
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.
IDBCursorWithValue - Web APIs
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.
IIRFilterNode.getFrequencyResponse() - Web APIs
next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then
loop through each data set and output them in a human-readable list at the bottom of the page: var feedforwardcoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackcoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirfilter = audioctx.createiirfilter(feedforwardcoefficients, feedbackcoefficients); ...
ImageData.data - Web APIs
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.
Intersection Observer API - Web APIs
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.
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).
KeyboardLayoutMap - Web APIs
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).
Recording a media element - Web APIs
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.
MutationObserver - Web APIs
// select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes: true, childlist: true, subtree: true }; // callback function to execute when mutations are observed const callback = function(mutationslist, observer) { // use traditional 'for
loops' for ie 11 for(let mutation of mutationslist) { if (mutation.type === 'childlist') { console.log('a child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log('the ' + mutation.attributename + ' attribute was modified.'); } } }; // create an observer instance linked to the callback function co...
Node - Web APIs
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).
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
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.
Performance API - Web APIs
performanceframetiming provides methods and properties containing frame timing data about the browser's event
loop.
RTCDataChannel.bufferedAmount - Web APIs
the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event
loop or truly asynchronously.
Report - Web APIs
we
loop over each report using a basic for
loop, then iterate over each entry of in the report's body using a for...in structure, displaying each key/value pair inside a list item.
ResizeObserver - Web APIs
resizeobserver avoids infinite callback
loops and cyclic dependencies that are often created when resizing via a callback function.
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
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).
SharedWorkerGlobalScope.close() - Web APIs
the close() method of the sharedworkerglobalscope interface discards any tasks queued in the sharedworkerglobalscope's event
loop, effectively closing this particular scope.
StylePropertyMapReadOnly.entries() - Web APIs
the stylepropertymapreadonly.entries() method 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 - Web APIs
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).
WebXR application life cycle - Web APIs
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.
Web Animations API Concepts - Web APIs
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.
Controlling multiple parameters with ConstantSourceNode - Web APIs
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 ...
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
we then
loop through this list — for each voice we create an <option> element, set its text content to display the name of the voice (grabbed from speechsynthesisvoice.name), the language of the voice (grabbed from speechsynthesisvoice.lang), and -- default if the voice is the default voice for the synthesis engine (checked by seeing if speechsynthesisvoice.default returns true.) we also create data- attri...
Window: popstate event - Web APIs
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.
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.
XRInputSource.gripSpace - Web APIs
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.
XRView.transform - Web APIs
ewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); for (let obj of world.objects) { mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, obj.matrix); mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); obj.render(modelviewmatrix, normalmatrix); } } two matrices are created outside the rendering
loop; this avoids repeatedly allocating and deallocating the matrices, and generally reduces overhead by reusing the same matrix for each object rendered.
Media events - Developer guides
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.
Index - HTTP
it is used for tracking message forwards, avoiding request
loops, and identifying the protocol capabilities of senders along the request/response chain.
Via - HTTP
it is used for tracking message forwards, avoiding request
loops, and identifying the protocol capabilities of senders along the request/response chain.
TRACE - HTTP
the http trace method performs a message
loop-back test along the path to the target resource, providing a useful debugging mechanism.
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
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.
Grammar and types - JavaScript
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.
Working with objects - JavaScript
e chain if (obj.hasownproperty(i)) { result += `${objname}.${i} = ${obj[i]}\n`; } } return result; } so, the function call showprops(mycar, "mycar") would return the following: mycar.make = ford mycar.model = mustang mycar.year = 1969 enumerate the properties of an object starting with ecmascript 5, there are three native ways to list/traverse object properties: for...in
loops this method traverses all enumerable properties of an object and its prototype chain.
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...
arguments[@@iterator]() - JavaScript
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.
Array.prototype.entries() - JavaScript
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.shift() - JavaScript
myfish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('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.
Array - JavaScript
common operations create an array let fruits = ['apple', 'banana'] console.log(fruits.length) // 2 access an array item using the index position let first = fruits[0] // apple let last = fruits[fruits.length - 1] // banana
loop over an array fruits.foreach(function(item, index, array) { console.log(item, index) }) // apple 0 // banana 1 add an item to the end of an array let newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let f...
Function.caller - JavaScript
(n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() the following is true: stop.caller === g && f.caller === g && g.caller === f so if you tried to get the stack trace in the stop() function like this: var f = stop; var stack = 'stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the
loop would never stop.
InternalError - JavaScript
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.
Object.freeze() - JavaScript
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.
Object.prototype.hasOwnProperty() - JavaScript
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()).
Promise.prototype.then() - JavaScript
return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread
loop).
RegExp() constructor - JavaScript
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.
RegExp - JavaScript
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.
String.prototype.codePointAt() - JavaScript
eproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined
looping with codepointat() for (let codepoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).tostring(16)) } // '1f40e', '1f471', '2764' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.codepointat' in that specification.
String.prototype.substring() - JavaScript
/ replaces olds with news in the string fulls function replacestring(olds, news, fulls) { for (let i = 0; i < fulls.length; ++i) { if (fulls.substring(i, i + olds.length) == olds) { fulls = fulls.substring(0, i) + news + fulls.substring(i + olds.length, fulls.length) } } return fulls } replacestring('world', 'web', 'brave new world') note that this can result in an infinite
loop if olds is itself a substring of news — for example, if you attempted to replace 'world' with 'otherworld' here.
Symbol.iterator - JavaScript
description 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.
TypedArray.prototype[@@iterator]() - JavaScript
examples iteration using for...of
loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of
loop // and let-scoped variables in for
loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecma...
TypedArray.prototype.entries() - JavaScript
examples iteration using for...of
loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of
loop // and let-scoped variables in for
loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, 20] console.lo...
TypedArray.prototype.keys() - JavaScript
examples iteration using for...of
loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of
loop // and let-scoped variables in for
loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().valu...
TypedArray.prototype.values() - JavaScript
examples iteration using for...of
loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of
loop // and let-scoped variables in for
loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next(...
WeakRef - JavaScript
that is, you can only "see" an object get reclaimed between turns of the event
loop.
eval() - JavaScript
"a.b.c" eval( 'var result = obj.' + proppath ); avoiding eval() here could be done by splitting the property path and
looping through the different properties: function getdescendantprop(obj, desc) { var arr = desc.split('.'); while (arr.length) { obj = obj[arr.shift()]; } return obj; } var obj = {a: {b: {c: 0}}}; var proppath = getproppath(); // returns e.g.
function* - JavaScript
; // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj = new f; // throws "typeerror: f is not a constructor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ //endless
loop to generate for(let current =n;; current *= n){ yield current; } } for(let power of powers(2)){ //controlling generator if(power > 32) break; console.log(power) //2 //4 //8 //16 //32 } specifications specification ecmascript (ecma-262)the definition of 'function*' in that specification.
let - JavaScript
the instruction let n of n.a is already inside the private scope of the for
loop's block.
return - JavaScript
function counter() { for (var count = 1; ; count++) { // infinite
loop console.log(count + 'a'); // until 5 if (count === 5) { return; } console.log(count + 'b'); // until 4 } console.log(count + 'c'); // never appears } counter(); // output: // 1a // 1b // 2a // 2b // 3a // 3b // 4a // 4b // 5a returning a function see also the article about closures.
<mi> - MathML
example italic (default value for a single character) ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال
looped ; مثال stretched ; مثال examples <math> <mi> y </mi> <mi> sin </mi> <mi mathvariant="monospace"> x </mi> <mi mathvariant="bold"> π </mi> </math> specifications specification status comment mathml 3.0the definition of 'mi' in that specification.
<mn> - MathML
mal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال
looped ; مثال stretched ; مثال examples <math> <mn> 0 </mn> <mn> 1.337 </mn> <mn> twelve </mn> <mn> xvi </mn> <mn> 2e10 </mn> </math> specifications specification status comment mathml 3.0the definition of 'mn' in that specification.
<mo> - MathML
mal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال
looped ; مثال stretched ; مثال maxsize if stretchy is true, this attribute specifies the maximum size of the operator.
<ms> - MathML
mal (default value) ; example bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال
looped ; مثال stretched ; مثال rquote the closing quote mark (depends on dir) to enclose the content.
<mtext> - MathML
bold ; example italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example normal (default) ; مثال initial ; مثال tailed ; مثال
looped ; مثال stretched ; مثال examples <math> <mtext> theorem of pythagoras </mtext> <mtext> /* comment here */ </mtext> </math> specifications specification status comment mathml 3.0the definition of 'mtext' in that specification.
Web audio codec guide - Web media technologies
possible exceptions include
looped music, where you need music to be able to play back uninterrupted over and over, or when you need to be able to play songs back to back with no gap between them.
Digital audio concepts - Web media technologies
use cases for lossless audio include scenarios such as: any situation in which the listener expects precise audio reproduction and may have an ear for sound that's good enough to make out the intricate details of unaltered audio audio
loops and samples used in music and sound effects production work situations in which audio clips or samples may be remixed and then compressed; using lossless audio for the mastering process avoids compressing previously compressed data, resulting in additional quality loss factors that may recommend the use of lossy compression include: very large source audio constrained storage (either beca...
CSS and JavaScript animation performance - Web Performance
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.
Web Performance
frame timing api the performanceframetiming interface provides frame timing data about the browser's event
loop.
Progressive loading - Progressive web apps (PWAs)
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.
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...
Tutorials
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.