And here sayHi() runs the function, and the result of its execution is passed to setTimeout.… The nested setTimeout is a more flexible method than setInterval.… Garbage collection and setInterval/setTimeout callback
When a function is passed in setInterval… The similar thing happens if we use setInterval instead of setTimeout: setInterval(f) runs f few times… Methods setTimeout(func, delay, ...args) and setInterval(func, delay, ...args) allow us to run the func
When the time is due for a scheduled setTimeout, the task is to run its callback.
…and so on.… setTimeout may be due and so on, these tasks form a queue, as illustrated in the picture above.… and so on.… Highlight the first 100 lines, then schedule setTimeout (with zero-delay) for the next 100 lines, and… The notable thing is that both variants – with and without splitting the job by setTimeout – are comparable
If the DOM-element of the logs display window is still accessible and kept in memory, create and send… unregistration of objects and their cleanup callbacks.… Creating “memories” and albums.
Video montage from a series of photos.
…and much more.… decide to change one of the images and create a new one.… implementation and operation of the garbage collector.
And asynchronous generators make it even more convenient.… Let’s see a simple example first, to grasp the syntax, and then review a real-life use case.… It calls range[Symbol.asyncIterator]() once, and then its next() for values.… object, so it’s both synchronously (for..of) and asynchronously (for await..of) iterable.… Then we can use that link for the next request, to get more commits, and so on.
That’s because setTimeout got the function user.sayHi, separately from the object.… What if before setTimeout triggers (there’s one second delay!) user changes value?… We can’t just omit the context and jump to arguments.… For example, to setTimeout.… a partial and go on with it.
The secret of reliability and simplicity of a coffee machine – all details are well-tuned and hidden… , and dangerous (it can electrocute).… Internal and external interface.In object-oriented programming, properties and methods are split into… Until now we were only using public properties and methods.… The code constantly undergoes development and improvement.
The underlying Range and Selection objects are easy to grasp, and then you’ll need no recipes to make… lt;b> and 3.… We’ve already seen setStart and setEnd, here are other similar methods.… Optional arguments start and end, if provided, set the range start and end, otherwise user selection… For input, textarea: additional methods and properties.
A Proxy object wraps another object and intercepts operations, like reading/writing properties and others… We don’t have to override value-adding array methods like push and unshift, and so on, to add checks… They are described in the article Private and protected properties and methods.… And very simple to implement.… object and the proxy.
Export and import directives have several syntax variants.… Most JavaScript style guides don’t recommend semicolons after function and class declarations.… It makes code support and refactoring easier.… modules together and optimize them to speedup loading.… Summary.Here are all types of export that we covered in this and previous articles.
from the chapter Garbage collection, JavaScript engine keeps a value in memory while it is “reachable” and… properties of an object or elements of an array or another data structure are considered reachable and… It occupies memory and may not be garbage collected.… Like Set, it supports add, has and delete, but not size, keys() and no iterations.… WeakSet is the absence of iterations, and the inability to get all current content.
Before we get into JavaScript’s ways of dealing with styles and classes – here’s an important rule.… JavaScript can modify both classes and style properties.… That’s more flexible and easier to support.
className and classList.Changing a class is one of the most… infers style.marginLeft and style.marginTop from it.… The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px
There may be any pattern instead of X and Y.… If it’s not so, then the potential match is skipped, and the search continues.… =\s), and there’s 30 somewhere after it (?… That is: match everything, in any context, and then filter by context in the loop.… , so we know where exactly in the text it is, and can check the context.
bold), and previous remembered contexts are below.… And the optimization may be unneeded and totally not worth the efforts.… And they, potentially, can split even more.… And that’s sometimes required to optimize stuff.… But for many tasks a recursive solution is fast enough and easier to write and support.
And so on upwards till the document object.… Normally it goes upwards till <html>, and then to document object, and some events even reach window… Don’t stop it without a real need: obvious and architecturally well thought out.… And there’s a logical explanation for that.… top element that handles general concepts and runs the last one.
When the browser loads the page, it “reads” (another word: “parses”) the HTML and generates DOM objects… But technically no one limits us, and if there aren’t enough, we can add our own.… The attributes collection is iterable and has all the attributes of the element (standard and non-standard… ) as objects with name and value properties.… What if we use a non-standard attribute for our purposes and later the standard introduces it and makes
New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended… to the list at https://tc39.github.io/ecma262/ and then progress to the specification.… It can parse (“read and understand”) modern code and rewrite it using older syntax constructs, so that… A transpiler would analyze our code and rewrite height ?? 100 into (height !… It “fills in” the gap and adds missing implementations.
Regular expressions are patterns that provide a powerful way to search and replace in text.… Regular Expressions.A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional… The “long” syntax:
And the “short”… And, finally, if there are no matches, null is returned (doesn’t matter if there’s flag g or not).… A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
It stores the date, time and provides methods for date/time management.… We can set out-of-range values, and it will auto-adjust itself.… So it’s faster and doesn’t put pressure on garbage collection.… And then you probably won’t need microbenchmarks at all.… Date and time in JavaScript are represented with the Date object.
That’s why Map and Set also exist.… So we should use map methods: set, get and so on.
Map can also use objects as keys.… And the standard iteration for map returns same key/value pairs as map.entries().… For example, we have visitors coming, and we’d like to remember everyone.… But this may help to replace Map with Set in certain cases with ease, and vice versa.
TextDecoder object allows one to read the value into an actual JavaScript string, given the buffer and… label – the encoding, utf-8 by default, but big5, windows-1251 and… …And then decode:
input – BufferSource… This options tells TextDecoder to memorize “unfinished” characters and decode them when the next chunk
A File object inherits from Blob and is extended with filesystem-related capabilities.… FileReader.FileReader is an object with the sole purpose of reading data from Blob (and hence File too… text string with the given encoding (utf-8 by default).
readAsDataURL(blob) – read the binary data and… The most widely used events are for sure load and error.… In addition to Blob methods and properties, File objects also have name and lastModified properties,
Let’s say we have a string like +7(903)-123-45-67 and want to find all numbers in it.… A quantifier is appended to a character (or a character class, or a [...] set etc) and specifies how… r looks for o followed by zero or one u, and then r.
So, colou?… r finds both color and colour:… Depends on how tolerant we can be to “extra” matches and whether it’s difficult or not to remove them
For instance, [a-z] is a character in range from a to z, and [0-5] is a digit from 0 to 5.… similar characters,
Join_Control (Join_C) – two special codes 200c and 200d, used in ligatures, e.g.… Unicode properties are covered in more details in the article Unicode: flag "u" and class \… They are denoted by a caret character ^ at the start and match any character except the given ones.… And if we need a backslash, then we use \\, and so on.
Specification.The ECMA-262 specification contains the most in-depth, detailed and formalized information… MDN (Mozilla) JavaScript Reference is the main manual with examples and other information.… To see their support among browser-based and other engines, see:
https://caniuse.com – per-feature tables… caniuse.com/#feat=cryptography.
https://kangax.github.io/compat-table – a table with language features and
They have some very specific and useful features.… It’s in the very spirit of JavaScript to create a function and pass it somewhere.… And in such functions we usually don’t want to leave the current context.… ctx so that the function inside setTimeout could take them.… And they really shine in that use case.
And if we increase it in setInterval, changing by 2px with a tiny delay, like 50 times per second, then… hence load less CPU load and look smoother.… It addresses all these issues and even more.… First we “pull the bowstring”, and then “shoot”.… It falls down, then bounces back a few times and stops.
Getters and setters.Accessor properties are represented by “getter” and “setter” methods.… It is readable and writable.… the access is done via getter and setter.… a setter and tweak its behavior.… We can try to find all such places and fix them, but that takes time and can be hard to do if that code
Run it and see what really happens.… and switches elsewhere.… ads and evils pages.… The main window and the popup can freely read and modify each other if they have the same origin.… Events focus and blur allow to track switching in and out of the window.
used one of them (admin) to get into it and make changes.… We’ll mention that in the chapter Property flags and descriptors.… and copying them on the primitive level.… user[key] and, if it’s an object, then replicate its structure as well.… Summary.Objects are assigned and copied by reference.
And it may be a better choice for such task.… down, and then keyup – when it’s released.
event.code and event.key.The key property of the event object… The event.key is exactly the character, and it will be different.… again, and then when it’s released we finally get keyup.… The browser opens the “Save Page” dialog (Ctrl+S)
…and so on.
The first thing to do is to locate quoted strings, and then we can replace them.… ; and her "broom".… So the first match is "witch" and her "broom".… and ??… , and so on… until it finally reaches " class="doc">.
But an object property is actually a more flexible and powerful thing.… In this chapter we’ll study additional configuration options, and in the next we’ll see how to invisibly… true, then listed in loops, otherwise not listed.
configurable – if true, the property can be deleted and… The returned value is a so-called “property descriptor” object: it contains the value and all the flags… returns all property descriptors including symbolic and non-enumerable ones.
Forms and control elements, such as <input> have a lot of special properties and events.… That’s a so-called “named collection”: it’s both named and ordered.… This is typical with radio buttons and checkboxes.… So a form references all elements, and elements reference the form.… We can use document.createElement('option') and set attributes manually.
So the sum is 284px plus left and right paddings, total 324px.… But as we know from the chapter Styles and classes, we can read CSS-height and width using getComputedStyle… And there’s one more reason: a scrollbar.… And clientWidth/clientHeight take that into account.… But Firefox shows 300px, while Chrome and Edge show less.
For instance, we have Article objects and need a function to compare them.… And for the second one we can make a static method of the class.… methods.Static properties and methods are inherited.… For instance, Animal.compare and Animal.planet in the code below are inherited and accessible as Rabbit.compare… As a result, inheritance works both for regular and static methods.
The for…of and for…in loops
A small announcement for advanced readers.… This article covers only basic loops: while, do..while and for(..;..;..).… See for…of and iterables for looping over arrays and iterable objects.
Otherwise, please read on.… , while it’s truthy, execute it again and again.… body
alert(i)
Runs again and again while the condition is truthy.
How do we find the width and height of the browser window?… How do we get the full width and height of the document, including the scrolled out part?… But there are additional methods and peculiarities to consider.… Width/height of the window.To get window width and height, we can use the clientWidth/clientHeight of… If it occupied some space, then that space is now free and the content “jumps” to fill it.
So, if we have a slotted element, and an event occurs somewhere inside it, then it bubbles up to the… <slot> and upwards.… All touch events and pointer events also have composed: true.… true for it to bubble up and out of the component.… …And so on.
They can be passed around, used as objects, and now we’ll see how to forward calls between them and decorate… …And for objects that are both iterable and array-like, such as a real array, we can use any of them,… Because we are calling hash(arguments), and arguments object is both iterable and array-like, but not… Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.… E.g. a decorator may count how many times a function was invoked and how much time it took, and expose
it is usually used to validate the form before sending it to the server or to abort the submission and… We can use it to dynamically create and send our own forms to server.… The handler can check the data, and if there are errors, show them and call event.preventDefault(), then… In the form below:
Go into the text field and press Enter.… Relation between submit and
We need to wait until the script loads, and only then we can call it.… It triggers after the script was loaded and executed.… …And what if the loading failed?… , save errors and provide an interface to access and analyze them.… Summary.Images <img>, external styles, scripts and other resources provide load and error events
The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”.… The caret ^ matches at the beginning of the text, and the dollar $ – at the end.… The pattern ^Mary means: “string start and… That is: two digits, then a colon, and then another two digits.… Anchors have “zero width”
Anchors ^ and $ are tests. They have zero width.
…and so on.
In this chapter we’ll learn how to do the same.… And also, how to pass arrays to such functions as parameters.… And it still works, we can find it in the old code.… And that would get ugly.
Spread syntax to the rescue!… and iterables.
and so on.… And then we can use it everywhere.… connected to DOM first, and then <inner>.… setTimeout triggers first, and then the inner one.… For instance, inner elements can dispatch events like initialized, and outer ones can listen and react
If the regexp doesn’t have flag g, then it returns the first match as an array with capturing groups and… the regexp has flag g, then it returns an array of all matches as strings, without capturing groups and… The swiss army knife for searching and replacing.… It will be called for each match, and the returned value will be inserted as a replacement.… …And so on.
If there are no matches, regexp.exec returns null and resets regexp.lastIndex to 0.
A browser supports not only HTML, but also XML and SVG.… For instance, DOMString, boolean and so on.… For instance, let’s compare tagName and nodeName for the document and a comment node:… As the content is “zeroed-out” and rewritten from the scratch, all images and other resources will be… And so on.
And, as it happens with strings, that may lead to odd results.… We’ll see that a bit later, in the article Sets and ranges [...].… And Number property means that it’s a digit: maybe Arabic or Chinese, and so on.… …And so on.… and {n} we’ll see how to look for numbers that contain many digits.
If you run it, you see code finished first, and… first and then caught.… We did catch and handle the error!”… In the example above, .catch added by setTimeout also triggers.… with the “event loop” and “macrotasks”.
['"], but it would find strings with mixed quotes, like "...' and '...".… looks for the closing quote exactly the same as the opening one, we can wrap it into a capturing group and… The regular expression engine finds the first quote (['"]) and memorizes its content.… Similar to that, \2 would mean the contents of the second group, \3 – the 3rd group, and so on.
Node.js provides server-side features, and so on.… stylesheets, that explains how they are represented as objects, and how to read and write them.… CSSOM specification
Describes stylesheets and style rules, manipulations with them, and their binding… various browser functions: setTimeout, alert, location and so on, see https://html.spec.whatwg.org.… It takes the DOM specification and extends it with many additional properties and methods.
Only first 50 results are shown.