Categories
Java Script Opinions

Release the thread

Changes in properties of element or manipulating the children elements will trigger updates in UI when you release the three

is virtual DOM really fast?

React claims that its virtual DOM implementation is proved to be faster than changing real Dom, where 10 changes are collected and real DOM is updated at once hence faster.

First of all, ten changes won’t trigger any change in real DOM until thread is released.

Layout change triggers on thread release

Single Thread

We have one main thread, our JS competes with the browser to use that thread.

If you are changing the same property 10 times, at same execution context, the real DOM will take the last change only.

That’s why

Zero Settimeout hack

Sometimes, I would see that angular code won’t change. It was addressed with following hack

    setTimeOut(() => {

}, 0)

Browser some times didn’t have enough time to make the change. Via this hack we defer the execution. We are basically running something out of main thread. setTimeout will put the callback method in callback queue, and with the help of event loop it will execute the callback

Another Example

For example you are listening to the event, in that event you making some UI updates, until the function, you aren’t releasing the thread.

After function ends, JS tells browser that do the rendering, Rendering goes through certain steps like reflow, repaint and so on to update the UI

Janky Scrolling

Sometime when you scroll though ecommerece on your mobile, the scrolling becomes stuck. This is due to JavaScript functions aren’t releasing thread. The browser don’t have enough time to detect the you are scrolling to Relayout the subsequent content

A code like while(true) will never release thread, some browser after few seconds will alert you

The site isn’t responding, should we kill it.

Element is added removed but isn’t reflected in UI

When you use DOM Api to Remove the node, it isn’t immediately reflected in UI. Even if remove it from DOM programmatically, it is displayed to the user, that’s because thread isn’t released, an element is removed from memory structure but yet to be reflected on the UI.

Conclusion

Thread is shared between browser and our JavaScript code. Which nothing happens in parallel, every thing happen in sequence. This behavior gives us predictability, and surety of how our code is executed. Which can be considered while writing the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.