All posts by admin

Event Loop (JS)

ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

So the runtime in our web browser works like so.

– We have a call stack that contains the execution contexts.
– We have a callback queue sitting and waiting.
– We also have a Web API section

  • Objects created in memory are stored in the heap.
  • Execution context happens on the callback.
  • We have a Web API that runs code used by the browser. It executes events and will place code in either the callback queue or other data structures.
  • We also have a callback queue that receives callback functions whenever an an event in the Web API is done or executed.

Say we start off with code like so

Thus, when we start the program, we start with an execution context for global scope.

It executes the first line of code, which is sync.
We then move on to the next line of code.

This will load up an image asynchronously. Thus, the loading of the image happens in the Web API and we let the async tasks run.

We move on to the next line of code:

So now, in the Web API, we have this callback function added. Our Web API keeps track of all these callbacks.

So here as you can see, Web API has the current async operation going…and maintains a callback. This is so that when the async operation of loading up the image is done, it has a valid callback to execute. The callback will stay there until load event is emitted. This is why we want to add the event listener for when the image finishes loading.

Having telling the Web API to load an image, and declaring a callback for when load is done, we now move forward to the fetch operation:

As always, the async fetch operation will happen in the Web API’s environment. Otherwise, we’d be blocking the call stack if we were to execute it using the execution context.

The Web API appends it to its running async operations and now have two async operations going:

Finally we use the then method returned by the fetch function. And this will also register a callback in the Web API’s environment. So we can react to the future resolved value of the promise.

In other words, we place the callback from then then in our Web API. This is so that when fetch operation is completed, it will know to execute the callback provided to then.

Now our Web API environment has two async operation working, and two callback to execute when they are done.

The execution goes forward and processes other code…

Now, comes the good part. Our loading of the image async operation is done! It signals with the load event. Load event has emitted. The callback for this event is then put into the callback queue.

Now, we DO NOT execute this callback right away. Instead, we now put this callback in the callback queue.

Callback queue is like a todo list. Whereas the event loop is an executor.

There could be other callbacks. Then our new callback would be queued and wait until the others are done. This callback will execute when the event loop has finished the other callbacks in the queue. It decides when each callback is worked upon.

This has implications.

Hence, keep in mind that if you decide to use setTimer and wait 5 seconds before putting a callback inside the callback queue, it doesn’t mean your callback will be executed at exactly 5 seconds later. It may be that the callback queue is still processing other queues in front. This will take whatever time those operations specify to be. And then, then they are done, the event loop will come to your callback and execute it.

Hence, when working with timers, just remember that the time you specify in milliseconds is the fastest time that your callback will execute.

Keep in mind that the callback queue also keeps callbacks from DOM events like clicks, or key presses.

DOM events are not async, but they still callback queue to run their attached callbacks. So if a click callback executes on a button with an event listener, it works in the same way that it stays in the event queue until others are finished. So if you somehow have a callback that takes some seconds IN FRONT of a button callback, then your button presses will not work. It will need for the hanging callback in the queue to finish, the event loop processes the button callback, which will then make your button presses work.

The event loop looks into the call stack. Aside from the global context, is it empty?

The Event Loop Tick

If the stack is empty, this means no code is being executed. It takes first callback from callback queue and put it onto the call stack to be executed. This is called the Event Loop Tick

It orchestrates javascript runtime.
Javascript language itself has no sense of time.
Everything that is async, does not happen in the engine.
Its the runtime that manages the async behavior, and it is the event loop that decides which code gets executed next.

The event loop got its name because of how it’s usually implemented, which usually resembles:

The Web API environment, the callback queue, and event loop all make it possible that async operations are executed in a non-blocking way, while using only 1 thread of execution in the engine.

The MicroTask Queue

Callbacks of Promises have priority over other callbacks by using the Microtask queue

So now say the data arrives, and fetch is done. Callback related to promises, actually DO NOT go into the callback queue. Instead, callbacks of promises go to a special queue for microtasks queue.

It is special because it has priority over callback queue. It will run ALL of the microtasks until it is empty. Only then will it process the callback queue again.

The way that it runs microtasks is the same as it would for callback queue. It puts the tasks onto the execution context to be executed. Note that if any microtasks add another microtask, then naturally the new microtask(s) will be processed until the microtask queue is empty. Only then will the callback queue continue to be processed.

Therefore, note that microtasks can starve a callback queue.

A Quick Example


output:

Test start
test end
Resolved Promise 1
0 sec timer!

If microtask takes long time to run, then our timer tasks on the callback queue will be blocked for that amount of time.

So as you can see there will be few seconds when Promise #2’s callback is executing on the microtask queue because the loop from our callback in Promise #2 is running. Once its done, it will log its text, and then finally, the timer’s callback will run on the callback queue.

output:

Test start
test end
Resolved Promise 1

…then a few seconds here because the loop from our callback in Promise #2 is running.

Resolved Promise 2
0 sec timer!

Additional Information

A JavaScript runtime uses a message queue

It is a queue that contains type Message.

Each message object in the queue has a reference to an associated function.
The Event Loop decides when to call the referenced functions.

queue.waitForMessage() waits synchronously for a message to arrive. Because Javascript is single-threaded, it can only do one thing at at a time. It can only processNextMessage if it has nothing to do (waiting).

But if a new message comes into the queue, it will be busy adding it to the queue. Thus in that situation, it cannot processNextMessage. It must first finish adding to the Queue. Then when no more Messages comes in, it will go into waitForMessage status, and thus be able to ProcessNextMessage

Processing Message

Each message is processed completely before any other message is processed.

Pro
This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).

This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.

Con
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the “a script is taking too long to run” dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.

How Message are Added

In web browsers, messages are added anytime an event occurs. An event occurs whenever we attach an event listener to the element like so:

We have an element with the id News. We put a click handler on that element. Now, whenever the user clicks on that element, we can process it the way we like.

When the click happens, an event occurs, and the callback function in the example gets added to the queue as a Message. Similarly, any other event will be added as well. If there is no listener, the event is lost.

Example

The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (default is 0).

The time value represents a delay in milliseconds. After the delay, the message (anon function provided) will then be pushed into the queue. In other words, when setTimeOut executes, the delay happens instantaneously. After two seconds, our anon function that logs hello will be pushed onto the queue.

If there is no other message in the queue, and the stack is empty, the message is processed right after the delay. However, if there are messages, setTimeout’s anon function will have to wait for the other messages in the queue to be processed. For this reason, the second argument indicates a minimum time — not a guaranteed time.

Basic setTimeout Example

The code gets executed synchronously. However, all async operations such as our setTimeout be placed into our queue. The thing is, Synchronously, our code gets pushed onto the queue first. Even though the setTimeout is wedged in between, the dely starts to run after our code is placed into the queue.

So the code gets pushed onto the queue. Async operations will obviously not run because it has to do the delay first. Thus, as the sync code is being run (our while loop), the 500 ms delay is happening. Then when the 500 ms is up, it then places the async operation (our anon function that logs) onto the queue. Let’s look at some drawings to depict this situation:

But since our while loop is still running, we can’t process the async function yet. We need for the while loop to finish running.

– First, we get a starting timestamp in seconds. Then use while loop to continuously get another timestamp in seconds.
– We subtract the second timestamp from the initial timestamp to get the difference.
– Because the difference is less than two, we repeat the loop. As time moves forward, this difference gets bigger.
– We keep doing this until the difference is two seconds.
– When this happens, we break out of the loop. This finishes our task in the queue.

The queue then remove our while loop, and then moves on to the next task, which is our console log.

Therefore, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument (delay) indicates a minimum time — not a guaranteed time.

From this example, you’ll be tempted to ask…if we change the dealay from 500 ms to 0ms, wouldn’t the function in setTimeout run exactly AFTER the first line of code?

OUTPUT:
Good, looped for 2 seconds
Ran after after 2 seconds

Thus, as the output shows, the answer is no.

Here’s why.

Zero Delay

Zero delay doesn’t actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn’t execute the callback function after the given interval.

The execution depends on the number of waiting tasks in the queue. In the example below, the message this is just a message will be written to the console before the messages in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time).

We enter all the synchronous code into the queue first. Then we place the setTimeout async functions in according to delay.

In our case, our 3 sync code lines starts executing. As its running, our delay of 0 starts for the setTimeout async operations. We immediately place cb1 function into queue.

Then the thread continues to process the sync code for a step. Then it comes back to our async operations and places cb1 anon function into the queue.

1) Puts the sync code (all 3 logs) into the queue
2) starts processing the sync code
3) delay of 0 is executed
4) logs ‘this is the start’
5) queue cb into the queue
6) logs ‘this is a message’
7) queue cb1 into the queue
8) logs ‘this is the end’
9) pops sync code
10) executes cb and logs ‘Callback1…’
11) dequeue cb
12) execute cb1 and logs ‘Callback2…’
13) dequeue cb1

Never Blocks

A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input. This is parallel programming. The single thread work between multiple tasks at the same time.

Legacy exceptions exist like alert or synchronous XHR, but it is considered a good practice to avoid them. Beware: exceptions to the exception do exist (but are usually implementation bugs, rather than anything else).

Mosh Redux part 6 (reduxjs toolkit’s slice)

redux toolkit also has slices, which combines createAction and createReducer.

So it automatically creates actions and reducers for us.

questions.js
let’s import createSlice

createSlice takes an object with properties name, initialState, and reducers.
name represent the feature of this reducer.
intialState is the starting point of the state.
Finally, we have a reducers property, which references an object. Inside this object,

In the previous approach, questionAdded was an object, so we can use [questionAdded] to check for the type.

In this approach, questionAdded is just a property. Slices automatically creates actionTypes and actions for us.

let’s look at this slice object.

We see the properties. We need to default export the reducer and export the actions.

So with this implementation we can remove the previous actions and reducers.

also need to export actions. We do so by extracting actions from slice.actions

Mosh Redux part 5 (cleaner code with reduxjs toolkit)

source code

Here we talk about a powerful library called redux toolkit

Open up a terminal and type:
npm i @reduxjs/toolkit

Redux toolkit provides a bunch of tools to simplify redux code.

One of them is for creating the store. Typically, we extract createStore from redux. Then put your reducers into createStore as a higher order function. We export this store to be used in our index.

If we use createStore way, we have do a lot of stuff manually.

But with redux tookit, we have a new way:

configureStore

We import our reducer(s) from our feature and insert via an object with property reducer:

A pro on using configureStore is that allows us to dispatch asynchronous actions.

Actions with less boilerplate

Typically we create actions by defining constants, then define objects with properties type and payload. The type property uses the defined constants.

However, there is a problem. Every action returns an action like so:

We manually create these by hand.
Redux toolkit has a function called createAction to do this for us.

Hence, in your action creator, we re-factor like so:

Now, in your reducer you can replace the type with our createAction.type:

Notice this:

When we use createAction to create our action object, the parameter we give to createAction is the payload object. Make sure we have properties ‘description’.

make changes in your index.js:

Improving the Reducers

A lot developers don’t like switch statements. Nor do they like returning immutable object patterns.
This is where we can use toolkit. We can create reducer without switch statements. Toolkit uses immer. Automatically translated to immutable update pattern.

Similar to createAction, we use library function createReducer.

When we call this parameter, the first parameter is the initial state

Under the hood, redux toolkit uses immer, so the manipulation of your state gets translated to immutable updated pattern.

Reminder: immer uses function product with initial state. It takes an argument draftState

draftState is actually a proxy. So it will record all changes applied to a copy of the initial state. Thus, preventing the manipulation of the original object.

Thus, our function:

is actually the draftState anonymous function that does the mutating.

By using the functionality from redux toolkit, you can streamline your code nicely:

question.js

Mosh Redux part 4 Writing clean Redux code (Dux Pattern)

source code

Let’s improve our file structure:

src/
action.js
actionTypes.js
reducer.js

Redux is all statement management. UI and Redux are two completely different concerns. Its like two supermarket sections.

That’s why we need to move all of our redux code to another separate folder:

src/
store/
-action.js
-actionTypes.js
-reducer.js

Let’s go further. Let’s group them into features. Each feature should have the standard action, actionType, and reducer files.

Dux Pattern – Bundle of action types, actions, and reducers for a specific domain. Instead of folders to group these three things together, we simply use one file. It is much more maintainable.

Implement Dux Pattern

In src, create store folder. In your store folder, create file called questions.js.

ducks pattern rules:
1) reducer must have ‘export default
2) export individual action creators
3) action types are implementation detail (no need for export)

so, action types:

action creators:

we export them so that other files can use them if need be.

Finally, our reducer, which needs to have ‘export default’:

Configuring the Store

Finally, in order to use our store, in index.js:

Now, your redux files with all those features won’t be cluttered. If you have ten features, you don’t have to scroll through 30 files. All you have is 10, and they’ve neatly packed their action, action types, and reducer into one file.

Mosh Redux Part 3 (Your own Custom Store)

Before moving, we should familiarize ourselves with how Redux is written from scratch.

Previously, when we log the store, we see the public interface with three main functionality:

– getState
– dispatch
– subscribe

Let’s try to implement them.

My Store

We hide our store variable in myStore. It is private.

Dispatch

Our reducer function gets passed into our constructor.
So we add a reducer parameter.

We create a dispatch function. So by scope, we access the passed in reducer function, and pass in action, and state. Remember in our reducer, we always return the new state. So we reference our state to the returned state.

Notify Subscribers (UI components)

When the state of the store gets changed, we want to notify the UI components. Hence we need these UI components be able to subscribe to our store.

Mosh Redux part 2 (Starter Redux app)

ref –

  • http://chineseruleof8.com/code/index.php/2019/01/03/functions-are-first-class-objects-js/
  • http://chineseruleof8.com/code/index.php/2019/01/05/currying-js/
  • source code

In Redux, we use functional programming paradigm. We use a lot of curry functions like so:

Pure functions

The qualities of a pure function is that there should be:
– no random values
– no current date/time
– no global state (DOM, files, db, etc)
– no mutation of parameters

Benefits are:

– self-documenting
– easily testable
– concurrency
– cacheable

Immutable

Cannot change the objects, but why?

PROS:
Predictability
Faster Change Detection
Concurrency

CONS:
Performance

We use assign to copy contents (properties, values) from one object to another.

There is an easier way is to do this copying of properties one object to another: spread operator.
We use the spread operator here so that person object’s name property and value “John” gets copied to a new literal object. We then add address property and value.
Finally when we log it, we’ll see the

However, it does a shallow copy. Let’s try to copy a object car.
Here when we use the spread operator on person object, it copies the value “John” and property name.
However, it doesn’t copy the object car. Instead, it copies the reference to that object to updated
Therefore, updated only has a reference to the object car.

We can prove this by updating updated.car.carName to “ford”. When we log person.car.carName, it is “ford”

Hence, spread operator does a shallow copy. It simply re-point address key/value to point to the object that person is referencing. So there’s only 1 object, but two references to it.

Create Redux app Tutorial

first, lets install redux: npm i redux@4.0

After installation, know that actions is what drives the store to keep your data.

It looks like this:

So as you can see, its basically an object with properties type and payload.

In order to take actions, we must create reducers.

Creating Reducer

Now that we know how actions are put together, we need to write a function in order to decide how we going to properly receive these actions.

In src, add new file reducer.js. A reducer is a function with parameters state and action. The role of the reducer is to return new state, based on incoming actions.

Hence in our case, we take in the action and look at its type. Depending on the type, we return a certain state.

Creating the Store

In src, create new file store.js In our file, we create the store, and then import the reducer because createStore is a first order function that takes in a function (reducer), and returns a store for you to use.

Dispatching Actions

Back in our index, we import our store and analyze its contents.
We use getState function to analyze what is in store in our state.
The initial state is set in our reducer. that is why we see an empty array.

index.js

We dispatch actions by inserting an object with properties type and payload.

Subscribing to the Store

Action Creator

dispatching actions takes all this typing and its too cumbersome. Let’s create an action file that does this for us.

Add new file called actions.js

We create another file to keep tract of the MACROS that we’ll be using.

Here, we create es6 functions that returns these action objects. That way our reducer can analyze these action objects to decide what to do next.

Now, in our reducer, we receives actions like below.

We receive the action object through the action parameter.

As you can see, its always 2 things:

1) analyze action’s type
2) return state with action’s payload

We use dot operator to copy over primitive types into our new state. However, if there are nested objects, then its only a shallow copy and we need to use libraries such as immer to create immutable state.

reducer.js

Mosh Redux part 1 (Introduction)

Redux is a state management library for JS apps

But why?

Keep different parts of the UI in sync.

Data flow one part to another and change. We need to write code to keep everything in sync. How data change? etc. Such issues shows that we need a state management library.

Instead of scattering all app state in various parts of the UI, we store inside a single source of truth. “Database for the Frontend”.

Solves problem of sync-ing data across the UI app.

  • Centralizes application’s state
  • Makes data flow transparent and predictable

Pros

Centralized state across UI
Predictable state changes
Easy debugging via Time travel debugging
Preserve page state
Undo/redo via Log Rocket

Con

Complexity
Verbosity

Mosh React Tutorial (part 6)

Stateless Functional Component

When your class component does not have any state or events, we can turn it into a stateless functional component.
Basically, it’s just a function that returns the render JSX.

Since we turn it from a class to a function, the ‘this’ will not apply because it becomes undefined. What we need to do is put props in the parameter, and React will pass the props in during runtime.

We first define a const NavBar reference to our state function. This reference cannot be re-assigned and must always point to our stateless functional component.

In the body of our arrow function, we return JSX.

So instead of having a class that extends Component, which gives us the usage of lifecycle methods, we simply define a function that returns a React Element.

That’s why we call this stateless. Dealing with simple stateless components, we dont’ always need all that is given to us by classes. We have the option of using stateless components.

shortcut: sfc

Also, notice that in class components, we can use the ‘this’ reference to refer to our component instance, and different calling environment, and context.

However, a stateless component has no state. This means that you can’t reach this. state inside it. It also has no lifecycle so you can’t use componentDidMount and other hooks.

Hence, you must pass props through the parameter. Due to it being an arrow function, the this is the parent context. The parent context of a state component is undefined. You cans imply log ‘this’ outside of your stateless component, and then log it again inside. You will get undefined on both accounts.

For example:

Destructuring Arguments

We can use object destructuring when it comes to props so that we don’t get props.—— all over our state components.

Similarly, we can also do this for prop usage in class components.

Now, anywhere we have this.prop…we can simply replace them with destructured properties.

Lifecycle Hooks

Our component go a through few phases during their life cycle. The first phase is Mounting phase. And this is when an instance of component is created and inserted into the DOM.

There are few special methods that we can add to our components and REACT will automatically call these methods. We’ll refer to these methods as Life Cycle Hooks.

Allow us to hook into certain moments during lifecycle of a component, and do something.

React will call these in order.

1st Lifecycle Phase: MOUNT

  • Constructor
  • Render
  • componentDidMount

This happens when state or props get changed.

2nd Lifecycle Phase: UPDATE

  • render
  • componentDidUpdate

3rd Lifecycle Phase: UNMOUNTING

  • componentWillUnmount

Let’s see them in action

Insert logs in Counter.js, and App.js for constructor and render.
You will see how React calls them in order.


— App constructor —
App render —
Counter constructor —
Counter rendering for Counter 1
Counter constructor —
Counter rendering for Counter 2
Counter constructor —
Counter rendering for Counter 3
Counter constructor —
Counter rendering for Counter 4
Counter constructor —
Counter rendering for Counter 5
App componentDidMount–

Mosh React tutorial (part 5)

to run: npm install, npm start
download source

Multiple Components in Sync

Under components, create a NavBar component.
Make it a basic component with a render and return empty JSX:

Go to getBootstrap, search for NavBar.

Locate a navbar you like and copy the HTML into our NavBar’s JSX.

Change ‘class’ to ‘className’.

Then import this NavBar into App.js to be used.

Finally, update our index.js to use App.js:


Now let’s look at our component tree. There’s no parent child relationship between Counters component and NavBar component.
Look at the diagram. How can we display total number of counters in our NavBar? In situations like this where there is no parent child relationships and you want to keep them in sync.

To solve this, we lift state of Counters component up into App, so that it can pass it to all its children.

Lifting State Up

First, we pull everything out from Counters, and put it in App

App.js

Since we brought the state object here, we can safely put handleIncrement and handleDelete here as well.
We pass in the Counters array to Counters component. In Counters component, we loop through that array, and use props to pass data down into each individual Component.

Notice that Counters have props onReset, onIncrement, and onDelete. These are callback functions that bubble back up to manipulate our parent array.

The callback onReset is passed to Counters to reset everything. The onIncrement and onDelete are passed into individual Counter components. A Counter component passes the component ID back up for us to increase or delete.

counters.jsx

Here in Counters component, we receive the counters array from App via props.
We then loop through each item in the array and pass associated data down to a Counter component.
We basically bubble events upward from Component. And then have App take care of them.

counter.jsx

Here is where we apply a lot of UI via css. Notice we do so by looking at the props object passed down from parent.
We use all the data passed down from the parent in order to draw and display what we want.

This is where we also receive events, and then send it up to our parent by calling function references on the props object.

In order to show that we have all the counters information, we display the # of counters with more than 0 value up in our NavBar: