<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dron Rathore on Medium]]></title>
        <description><![CDATA[Stories by Dron Rathore on Medium]]></description>
        <link>https://medium.com/@dron?source=rss-1c68ab1c361f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JzX9DE0iactz0tsUdalKgA.jpeg</url>
            <title>Stories by Dron Rathore on Medium</title>
            <link>https://medium.com/@dron?source=rss-1c68ab1c361f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:50:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dron/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Discovering Silence — Life in Denmark]]></title>
            <link>https://medium.com/series/discovering-silence-life-in-denmark-ba4cf48c761b?source=rss-1c68ab1c361f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4cf48c761b</guid>
            <dc:creator><![CDATA[Dron Rathore]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 19:18:59 GMT</pubDate>
            <atom:updated>2018-04-01T15:17:00.814Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my experience of being an outsider and feeling of loneliness that I face being in Denmark. This series is written after numerous soul-searching tours to Aarhus Harbour and sitting under the clear sky, the series may keep on expanding as and when I end up accumulating enough thoughts to write down again. :)</p><p>Just a prelude, Aarhus is a beautiful city hands down, I love the city, the clear skies(when there is one), the dusty aroma that it bears is soothing and relaxing. Also the never ending common names like Jeppe, Martin and Jacob, you need to add a surname to give perspective when you are referring them.</p><h3>Excitement and Reckoning</h3><p>When I left India, I was so excited to be in Denmark, the experience of new life, new friends, and it didn’t took much time for the reckoning to hit me, the moment I landed here, something inside me whispered that I don’t belong here. Sure the girl who talked to me from Amsterdam to Billund was very kind enough to start the conversation and then later our conversation ended up in erring silence for no apparent reasons. The lady at the airport who shrugged me for asking directions, I kind off took them as just coincidence of human behaviour while ignoring my psychological instinct of seeing the pattern. Oh Boy! What did I just signed up for!?</p><h3>Language</h3><p>The first and foremost thing that isolate you the moment you land here is the language, it’s not that people don’t know English, but it’s not the preferred language here, just like back in home country. I once got called out for being a downer by a couple of girls outside my apartment just because I didn’t knew Danish.</p><p>The customer care numbers asks you to press <em>SU</em> to talk to the customer care team, and you curse yourself just a bit more for that, the websites, menu-cards in restros and every daily use commodity are printed in Danish which you keep on trying to translate with your Google Translate app, you literally feel like a Martian kept inside a simulation for test.</p><h3><strong>Learning Danish — The </strong>dilemma</h3><p>I like different languages, and to be honest Danish isn’t the one that stuck my chord of curiosity, yet. Sure it’s the requirement to survive in this society but still. For starters each word has multiple meaning, depending on the suffix and prefix that you use. Deal breaker, most of the time even Danish people are not always sure about the grammar and phrasing of sentences. I would gladly restart my German classes over Danish. Maybe I will give Danish a try if I find a better teacher, but for now, I have to adjust without it. I have learned my way to say <em>Ya</em>, <em>Nej</em> when I hear the lady at Netto saying something in Danish which translates to “<em>Hey do you need the bill?</em>”, that’s the best 1-to-1 Danish conversation I am having these days.</p><h3>Alcohol</h3><p>Let’s just put it this way, Anything that has alcohol in it, Denmark loves it, people’s obsession with Red Wine, Beer and almost any other drink is simply incomprehensible for me. I am a non-alcoholic guy, I prefer being high on life rather than being high for 3–4 hours on a weekend and then go back to sleep just to wake up and realise that my life is at the same shitty level as it was before last night, unless you end up picking a women in which case you just signed up for Level 2 of absurdity in your life.</p><h3>To be or not to be — Dilemma No. 2</h3><p>I have been persuaded to drink alcohol in my life many times, but never have I felt isolation because of it, the isolation that you face in Denmark for the same is beyond imagination. Chucking a few drinks with your Danish/European friends is a pre-cursor to be in their friend circle or at least to find another human-being to talk your heart out, if you don’t drink then you are just a dummy who isn’t fun to be around, you got no stupid stories to tell when last time you were piss drunk, which was last weekend, so *shrug*.</p><h3>Food</h3><p>Pork, Bacon, Beef, Duck, Veal you name it and Denmark has it. The menu is so full of meat that you wonder how this country manages to produce so many animals to even out the consumption.</p><h3>To be or not to be — Dilemma No. 3</h3><p>I am a vegetarian, boom.. there it is. My colleagues have to search and double check a place if they have some grasses for me to eat before we head out to eat there, I am official goat in the group. When the office chef is on vacation it becomes worse, the catering company makes sure I end up eating a bread loaf with some butter on top of it. I have been persuaded to join the tribe but with no heeds. This thing of being a vegetarian makes sure that your isolation level increases by 10X. Congrats you just unlocked the skills to be a perfect loner. But hey! I love cooking so its always good to experiment things and burn some mashed potatoes on weekends.</p><h3>Friends back home</h3><p>Hmm.. so I guess now I have got to a point in my life where I can validate the thought that long distance friendships are never meant to work out. You have time zone, you feel disconnected with their thoughts, and you just can’t communicate all that you want to, about how you feel, how deeply in need of mental peace you are. You just can’t convey all of that on a FaceTime or an audio call.</p><p>And to be honest everyone is getting settled in their own personal life, so carving out time for you is hard for them too.</p><h3>Colleagues at Work</h3><p>I must admit my colleagues at work are super awesome, my workplace is the reason why I sometime feel that weekends shouldn’t exist.</p><p>However every one has their own personal life, wife or girlfriend, except me and Daniel(sorry Daniel :)), so they all are embodied in performing their duties.</p><p>So you are left with one option, seek friends outside your workplace, but how do you do that when you are at 100X isolation level? Good Question. I am looking forward to your answers because I haven’t found any.</p><h3>The Reckoning</h3><p>I didn’t intended to write this sad post but well then after ample frustration from getting my worst haircut, and 2 Magnum sticks down, the hormones in my body aligned in a perfect order ending up in publishing this post.</p><p>I know my life will get more silent as I move ahead in coming years, Silence, deep and complete silence, the only gift I have received. Silence is good, but sometimes it can turn depressing, it can trigger existential crisis in your life.</p><p>And to be honest I am coming at terms with this erring silence, slowly, it is becoming part of my life, the very fact I hate the most.</p><p>It’s not that I am not fun, or I am too serious in life, ask the Grillen Burgerbar lady about the Tabasco smelling guy, she thought I was piss drunk at their shop where I just didn’t got much sleep. Well that’s true I am fun when I want to be fun. But cmm’on!</p><p>That’s it for now. It will take another months of enlightening trips to the Aarhus Harbour for me to write and expand this series, but I will try my best. For now I will slide back to listening to <a href="https://www.youtube.com/watch?v=pIQLha4zcQI">this</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4cf48c761b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NaN is not equal to NaN!]]></title>
            <link>https://medium.com/engineering-housing/nan-is-not-equal-to-nan-771321379694?source=rss-1c68ab1c361f------2</link>
            <guid isPermaLink="false">https://medium.com/p/771321379694</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[integer]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nan]]></category>
            <dc:creator><![CDATA[Dron Rathore]]></dc:creator>
            <pubDate>Sun, 30 Oct 2016 19:45:22 GMT</pubDate>
            <atom:updated>2021-08-12T13:08:52.229Z</atom:updated>
            <content:encoded><![CDATA[<p>Yeah, a Not-A-Number is Not equal to itself. But unlike the case with undefined and null where comparing an undefined value to null is true but a hard check(===) of the same will give you a false value, NaN’s behavior is because of IEEE spec that all systems need to adhere to. In this blog I will throw some light on NaNs and how they are implemented in the v8 engine.</p><blockquote>Short Story: According to <a href="https://en.wikipedia.org/wiki/IEEE_floating_point">IEEE 754</a> specifications any operation performed on NaN values should yield a false value or should raise an error.</blockquote><h3>What is a NaN?</h3><p><em>As per IEEE standards any value with all bits of the </em><strong><em>exponent</em></strong><em> set to 1 and at least one bit of the </em><strong><em>fraction/mantissa</em></strong><em> set as non-zero, represents a NaN.</em></p><p>To understand the above, we need to look at the basics of how numbers are saved in memory. IEEE 754 outlines the basic standards and computational algos to work with numbers or floating point numbers, explaining the complete 754 will take a separate blog altogether which I will write later on, for now lets just get an overview of it to understand NaN’s definition.</p><p>In a scientific representation of any number, a number has a sign(+/-), a mantissa and an exponent. For e.g.</p><p>A base 10 number 1.234 in scientific representation can be written as 1234 * 10^-3, where 1234 is a mantissa/<a href="https://en.wikipedia.org/wiki/Significand">significand</a> and 10^-3 is the exponent.</p><p>IEEE suggests the use of the similar representation to save numbers in binary format, for a single precision float value the IEEE format is given as</p><pre><br>| <strong>sign bit</strong> | <strong>exponent</strong> | <strong>mantissa</strong> |</pre><pre> <em>where</em>,<br>  sign bit = <strong>0</strong> | <strong>1</strong><br>  exponent = <strong>-127</strong> to <strong>+128</strong><br>  mantissa = <strong>24 bits</strong> of significand value<br></pre><p>Numbers can be written in 2 formats in accordance to the above representation</p><pre><strong>Single</strong>: SEEEEEEE EMMMMMMM MMMMMMMM MMMMMMMM<br><strong>Double</strong>: SEEEEEEE EEEEMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM</pre><p>So a NaN value according to the definition(all exponent set to 1 and at least one fraction bit set) can be represented as:</p><pre><strong>| 0 | 1111111</strong> | <strong>00...01<br></strong><em>or<br></em><strong>| 0 | 1111111</strong> | <strong>10...00</strong></pre><blockquote>Tip: Exponent value -127 and +128 are used for reserved category, NaN is +128.</blockquote><h3>Types of NaN</h3><p>There are 2 types of NaN, one can speak another one cannot.</p><h4>Quiet NaN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*8LhDLCRn_2cc72Y9rtFPEQ.png" /><figcaption><strong>These are good NaNs, Brent!</strong></figcaption></figure><p>A Quiet NaN is simply any NaN value that doesn’t raise error and can flow through your code by falsifying value or converting itself to a string.</p><h4>Signaling NaN</h4><p>This one can talk, NaN values in this case will raise or <a href="http://en.cppreference.com/w/cpp/types/numeric_limits/signaling_NaN">set error</a> for the user to handle it, most of the strongly typed languages make use of signaling NaNs.</p><h3>Implementation of NaNs</h3><p>NaN’s implementation and differentiation between quiet and signaling NaN is often left on the underlying system, <strong>std::numeric_limits</strong> helper is generally used in C++ to yield a NaN value, if you drill down in the header files of <em>std</em> you will find out the default implementation hidden deep inside the file <a href="http://opensource.apple.com//source/Libm/Libm-315/Source/PowerPC/math.h"><strong>math.h</strong></a><strong> </strong>which in turn make use of builtin functions of <a href="https://android.googlesource.com/platform/ndk/+/5de42e6621b3d0131472c3f8838b7f0ccf3e8963/sources/cxx-stl/llvm-libc++/libcxx/include/support/ibm/limits.h"><strong>limits.h</strong></a><strong> </strong>which looks like this</p><pre>// Quiet NaN</pre><pre>// float NaN<strong><br>static</strong> <strong>const</strong> <strong>unsigned</strong> <em>int</em> _QNAN_F = <strong>0x7fc00000</strong>;<em><br></em>// long double NaN<strong><br>static</strong> <strong>const</strong> <strong>unsigned</strong> <em>int</em> _QNAN_LDBL128[4] = {<strong>0x7ff80000</strong>, <strong>0x0</strong>, <strong>0x0</strong>, <strong>0x0</strong>};</pre><pre>// Signaling NaN</pre><pre><em>// </em>float NaN<strong><br>static const unsigned</strong> <em>int</em> _SNAN_F= <strong>0x7f855555</strong>;<em><br>// double NaN<br></em><strong>static const unsigned</strong> <em>int</em> _SNAN_D[2] = {<strong>0x7ff55555</strong>, <strong>0x55555555</strong>};<br>// long double NaN<strong><br>static const unsigned</strong> <em>int</em> _SNAN_LDBL128[4] = {<strong>0x7ff55555</strong>, <strong>0x55555555</strong>, <strong>0x0</strong>, <strong>0x0</strong>};</pre><p>The differentiation between multiple types of NaN is done on the basis of their masked bits. If you see the above code closely you will find out that all the values adhere to the initial definition of NaN as defined by IEEE 754.</p><h3>NaNs in v8</h3><p>In v8 compiler all data types are characterized and saved with a proper bit assigned to it so as to boost the runtime comparison and operations, NaNs are no <a href="https://github.com/v8/v8/blob/master/src/compiler/types.h#L115">exception</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*W5B0OUhPkCkT44e2ayOExQ.png" /><figcaption>negative Zero is a thing!</figcaption></figure><p>v8 also make use of <strong>std::numeric_limits </strong>helpers of C++ to define NaN values, however v8 too have its own custom NaN <a href="https://github.com/v8/v8/blob/master/src/arm64/utils-arm64.h#L88-L122">helpers</a> which works in a similar fashion. In v8 a NaN value can be encountered at 2 levels, one is at compile time and another at runtime, lets have a look at both.</p><h4>Compile Time NaNs</h4><p>Whenever the v8 compiler encounters a NaN constant value during compilation/graph creation it automatically <a href="https://github.com/v8/v8/blob/master/src/compiler/js-graph.cc#L123">assigns</a> the value of a quiet NaN to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUGHgrwL1JoC4eXwgGsg-w.png" /></figure><h4>Runtime NaNs</h4><p>During runtime a quiet NaN value could be returned by <a href="https://github.com/v8/v8/blob/master/src/runtime/runtime-numbers.cc#L52">parseInt</a> and <a href="https://github.com/v8/v8/blob/master/src/runtime/runtime-numbers.cc#L80">parseFloat</a> or they could be returned by any <a href="https://github.com/v8/v8/blob/master/src/compiler/operation-typer.cc#L619">math operation</a> or a MIPS <a href="https://github.com/v8/v8/blob/master/src/compiler/mips/code-generator-mips.cc#L1230-L1273">check</a>.</p><p>All variables in v8 are typed, there are 2 Typer classes which does the task of typing of variables, <a href="https://github.com/v8/v8/blob/master/src/compiler/typer.cc">one</a> belongs to TurboFan and <a href="https://github.com/v8/v8/blob/master/src/asmjs/asm-typer.h">another</a> one is the ASMTyper, to understand typing and v8 compiler flow you may enjoy <a href="https://twitter.com/bmeurer">Benedikt’s</a> <a href="https://docs.google.com/presentation/d/1H1lLsbclvzyOF3IUR05ZUaZcqDxo7_-8f4yJoxdMooU/edit">slides</a>.</p><p>Its these typers which are responsible for type checking your variables before evaluating them, so for a comparator call on a NaN value you will end up triggering <a href="https://github.com/v8/v8/blob/master/src/compiler/typer.cc#L825">this</a> in TurboFan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhwh3XlnE1I3fT6edAUPWw.png" /></figure><p>If either of the RHS or LHS value is NaN, comparator will always return false, which is right keeping in mind the IEEE spec. By default NaNs in JS are quiet NaNs so if future TurboFan compiler wants to add signaling NaNs functionality then they will just check for the masked bits and then trigger the error.</p><p>Oh are we done? Damnit!</p><p>Yeah folks that’s it, a dive inside the little world of our NaNs, they now feel so special.</p><p>And wait, you might sometime end up with NaN values becoming 0.0000 if you compile your C++ code with <strong><em>-ffast-math</em></strong> flag on Intel processors.</p><p>(╯°□°）╯︵ ┻━┻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771321379694" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineering-housing/nan-is-not-equal-to-nan-771321379694">NaN is not equal to NaN!</a> was originally published in <a href="https://medium.com/engineering-housing">Engineering @ Housing/Proptiger/Makaan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oh my TimeOut!]]></title>
            <link>https://medium.com/@dron/oh-my-timeout-257f1d909e7c?source=rss-1c68ab1c361f------2</link>
            <guid isPermaLink="false">https://medium.com/p/257f1d909e7c</guid>
            <dc:creator><![CDATA[Dron Rathore]]></dc:creator>
            <pubDate>Sun, 08 Feb 2015 18:45:35 GMT</pubDate>
            <atom:updated>2015-02-09T04:14:30.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxpXBjXht4gD09JMwVIh8w.jpeg" /><figcaption>Time is immortal!</figcaption></figure><p>Hi,</p><p>One of my friend commented on my previous post and suggested that I should explain a bit about the Timers, so here it is.</p><p>What is Time? Umm.. A measurement from a reference point in history? Or that counted using Radium? Whatever, it doesn’t really matter, unless we start to have bad times in life, does it? Well its kind of cool question that you can look around the web and figure out the exact answer about this fourth dimension.</p><p>First, I remember saying there was one homework that I suggested in my previous post, got your hands on it? Oh well, no worries! ☺</p><blockquote>A typical number of Stack values that JS engines can store is 5,00,000 for Firefox Ion Monkey, 1,25,471 is for Chrome and 1,21,320 for v8 based NodeJs. These are the number of arguments that you can actually pass to a function in Javascript, now do a quick math and figure out what does each number signifies or doesn’t at all.</blockquote><p>What? You haven’t read the previous post? <a href="https://medium.com/@dron/should-i-call-or-should-i-apply-6650a4352206">Here you go</a>.</p><h4>What are Timers?</h4><p>Timers plays a vital role in computer science, actually they are the one responsible to drive your system, remember that button cell embedded on motherboard chipsets? CR2032 lithium coin cell helps in ticking the clock of your system. Okay, so here we are gonna discuss about the Timers in Javascript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/778e3476811c5c4c9c7011f180ce1673/href">https://medium.com/media/778e3476811c5c4c9c7011f180ce1673/href</a></iframe><p>Try changing the length of the Array in the second case and you will see the change in the Timeout fire time.</p><p>Javascript engines doesn’t have Timers inbuilt in them, they rely on other libraries or frameworks that implement them e.g. Firefox uses NSPR(Netscape Portable Runtime), v8 has internal built in support for them.</p><p>We will be taking NSPR for the purpose. So, lets see what a Timeout is:</p><h4>Browser Model</h4><p>Browsers works on an event queue model, where all the events gets queued and then browser picks up one entry from the queue at a time and execute it, to visualise, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Nb61eaApgbP-1OF9JzXy0g.gif" /></figure><p>So what are timers? They are threads, that are timed after which they push callback in the event queue and waits for its chance to get executed, so if you are doing some blocking task, allocating big memory chunk, looping over a big set of data, the chances of your callback getting delayed increases.</p><p>The thread library that Netscape uses is a customised form of pthread, they have a wrapper above it which they named <a href="https://github.com/servo/nspr/blob/master/pr/src/bthreads/btthread.c">BThread</a>(Binary Thread, I guess), it handles all of the TLS(Thread Local Storage) and Code contexts that needs to be triggered.</p><p>To provide the thread usability, the underlying engine of Firefox i.e. Gecko uses<a href="https://github.com/mozilla/gecko-dev/blob/master/xpcom/threads/nsThread.h"> XPCOM and interface</a> it with the core JS Engine(what are these? will cover them later in a separate blog).</p><h4>set(Interval|Timeout)(callback, integer)</h4><p>If we talk about JS, then we have only 2 options to have Timers i.e. setInterval or setTimeout</p><blockquote>Law: Interval = Timeout (somewhat)</blockquote><p><em>setTimeout</em>, <em>setInterval</em> returns you the Unique Id of the Timer, and the cool thing, two consecutive setTimeout/setInterval will never have a sequential ID’s(Why? that’s today’s homework☺). These ID’s are integer values that means you can add, subtract, divide, multiply there values, but be careful don’t loose those values.</p><p>Actually, <em>setInterval</em> simply means to trigger your callback after a certain amount of time, right? And timeout means to execute a callback after a certain time with little difference, Interval is repeating and Timeout isn’t, but functionally both are same thing. So why can’t Timeout be made subset of Interval? That is called smart work ☺ rather then writing a complete new implementation, <a href="https://github.com/mozilla/gecko-dev/blob/master/dom/base/nsJSTimeoutHandler.cpp">browsers utilise</a> Timeout to simulate the Interval Timers.</p><h4>clearInterval(ID)/clearTimeout(ID)</h4><blockquote>Law: clearInterval = clearTimeout</blockquote><p>Well, you might not agree with my law stated above, right? Let me prove it for you :D</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae211031f9fd16333f904b59f3ac6622/href">https://medium.com/media/ae211031f9fd16333f904b59f3ac6622/href</a></iframe><p>Hahaha :D Yeah, they both are same thing, just as setInterval and setTimeout. They take the Unique ID’s that <em>setTimeout</em>/<em>Interval</em> returns to you. Simple Job, they just kills the thread, GC everything, clean memory.</p><h4>Timer Frames</h4><p>Well your Timers will rarely be fired in time, because there will be dozen of things that you will be manipulating on DOM, right? Like your event listeners, they too push on queue there callbacks, similarly are your Ajax callbacks, HTML5 API’s callbacks. They all run in that single Event Loop, so probability of timers been fired in time is very low. In the end only one callback is been executed by the DOM, and if you add something like a very big for loop, everything will hang up, because the event loop will never reach the end of current callback and could never pick up the next queue item, and your complete window will freeze!(Try it!)</p><h4>Animations &amp; Frames</h4><p>Previously when <em>requestAnimationFrame</em> function wasn’t available to the developers, we use to create our animations using setInterval(), well today also you can create animations using setInterval but they seems to be bit laggy if you compare them with that what you can achieve with CSS3 animations.</p><p>Okay, so let’s study about what are Animations Frames.</p><p>CSS Animations and <em>requestAnimationFrame</em> works in a different domain and are different from Timers library which <em>setTimeout</em> and <em>setInterval</em> uses, Oh not the beneath library i.e. bthreads/pthreads but the <a href="https://github.com/mozilla/gecko-dev/blob/master/layout/base/nsRefreshDriver.cpp">interface which they use</a>. The <em>requestAnimationFrame’s</em> main motive is to achieve 60fps(Frames per second) rate of Animation, unlike JS Timers which can be delayed because they are working into a single event model natively.</p><p>Animation Frames are moved outside it to achieve this because of limitations that we face in ordinary Timers. But still the animation frame code execution depends on the manipulation you will be doing in the callback of <em>requestAnimationFrame</em>.</p><p>The Animation Frames are allocated a separate Queue Model and handler, in order to speed up the Animation CallBacks, it utilises a perfect approach of nextTick() which nodeJS uses with a difference, nodeJS looks it under process.nextTick(), which is like looking for a time frame when in the next turn process will be idle whereas the Animation Frames Ticker is ticked after ever 1ms, it looks into the queue, fire all the handlers, sleeps for 1ms and then again, pick up all the animation callbacks in the queue and fire them.</p><p>Now, let say you pushed a callback at Time T in the event Queue, at</p><blockquote>T = t</blockquote><p>Browser will pick up that callback from the queue and will fire it after 1ms,</p><blockquote><em>T = T+1ms</em></blockquote><p>Now this callback execution time defines the next time cycle, so let say your callback took 3ms to complete its execution.</p><blockquote>Next Queue Time(T) = T+1+3</blockquote><p>Although in between those 3ms, browser has checked the event queue thrice, but your callback wasn’t queued back until then, in the next 1ms cycle, browser will again check the event queue and this time it will find your callback there, it will fire it, and the cycle repeats.</p><p>Eventually, you will have a delay of 3ms at each cycle, In a fraction of second Browser checks the event queue at 60Hz(60fps) rate, i.e. after every 1ms. As your timers have delayed for 3ms at each cycle, eventually in 1 second, it will be fired only ~30 times which is a 30Hz(fps) rate of animation, it will be laggy, a lot!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/899abae20d1284f09cc414bed30100e2/href">https://medium.com/media/899abae20d1284f09cc414bed30100e2/href</a></iframe><p>In the above code the callback function <em>step </em>is what will determine the next callback time valuation, however, the DOM’s goal to fire the event listener is to fire your callback in time and not to wait but you know Threads sharing same memory space and memory can have an awkward behaviour, so browser waits until your callback get fired before firing your callback. So while writing tedious animation and to achieve 60fps, just make sure your callback completes its task in 1–2ms. To optimise things, browsers suspend Animation Frames if they don’t have focus to save memory and utilise more GPU/CPU for other tabs.</p><p>Well if you really need an exact ~1ms timer to perform some task/animation, <em>requestAnimationFrame</em> is your bet!</p><p>Still laggy? Need even better animation? Use CSS3 animations! There callbacks don’t compute, they just get fired! The only drawback is control, you can’t control behaviour of your animation frames that’s why browsers exposed requestAnimationFrame interface.</p><h4>Conclusion</h4><p>Timers are pretty fun thing but everyone knows, no one can ever have real time timers(atleast on nano scale and sometimes on micro, it depends), real time systems rarely exists, so we should use the time frame provided to us very efficiently, well I might sound like a philosopher but this same thing applies to our life too! ☺</p><blockquote>Quest: What makes your CPU burn too much calories when you run a high graphic animation in your browser or system?</blockquote><blockquote>Well, its the number of threads actually, which are responsible for it who are all painting the screen/refreshing the screen simultaneously. In a game, there are several threads that are working at a time, Shaders, Texture Loaders, Movement Controller, Bot Controller, they all are individual threads(or multiple of them, depends upon the architecture which developer choose) which are performing a load of computational tasks on CPU, and there are almost more then 10000 contextual switches it has to perform to keep everything running and in sync in 1ms.</blockquote><p>Oh yeah, here is our little child browser, pitty on him, but thats the only model he found best(so as NodeJS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JevJJ4Yio4okaOlR2PiNSQ.gif" /><figcaption>Firing Callbacks one after another!</figcaption></figure><p>That’s it for this week, let me know, what you feel about the blog, things I should improve/focus more on. Leave your comments and let me know what should I write next.</p><p>Happy Weekahead!</p><p>❤ Love! ☺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=257f1d909e7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should I call() or Should I apply()?]]></title>
            <link>https://medium.com/@dron/should-i-call-or-should-i-apply-6650a4352206?source=rss-1c68ab1c361f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6650a4352206</guid>
            <dc:creator><![CDATA[Dron Rathore]]></dc:creator>
            <pubDate>Sun, 01 Feb 2015 15:07:35 GMT</pubDate>
            <atom:updated>2015-02-01T15:07:35.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxpXBjXht4gD09JMwVIh8w.jpeg" /><figcaption>Seriously, I will ☺</figcaption></figure><p>This question was always on my mind, but I never tried my hands on really getting into what actually makes the difference between two, or more precisely why these 2 happens to be in Javascript when we can do the same task with any of them? Also the biggest question is why they have a difference in their performance?</p><p>For a layman who is in hurry to read this blog, the answer is.</p><blockquote>The difference between call and apply can be visualised as, you have a stick and you call your dog’s name and throw that stick towards him and dog grabs it, no hassle, simple task isn’t it? That’s call(). Another way could be, you call the name, let him come to you and then you can give him as many sticks as you want or none at all. Now here sticks refer to the 2nd arguments that you pass to the call() and apply() function i.e. list of arguments</blockquote><p>Lets have a look at this small code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78c7c6435240c4732d974f170c67faf/href">https://medium.com/media/a78c7c6435240c4732d974f170c67faf/href</a></iframe><p>Now some might question about the GC cycles, but trust me you can explicitly call GC by either calling <strong><em>delete somObj</em></strong><em> </em>which is the worst way of doing it, rather you can reuse the same variable by either assigning <strong><em>null </em></strong><em>or </em><strong><em>undefined </em></strong>but you will find an equal variation of time for both call() and apply().</p><p>Okay, lets get to the problem, you can try running the benchmarks and you will find out that <em>call() </em>is far more optimised then <em>apply()</em>. You will find similar benchmarks all over the internet but everyone says that “<em>JS internally optimise it” </em>but being a programmer you should be able to answer the question, How? In this blog I am gonna do the same, answering the quest of the solid proof as why they two happen to be in JS and why one is more optimised then another.</p><p>First of all we need to understand how Javascript actually works, now as we have learned from internet and our books we might say, its an Interpreted language, true that i.e. No need to compile, generate a binary and then execute it the way we use to do for compiled languages e.g. C, C++, Java, Go, Rust e.t.c., instead the code gets compiled on the fly while you are executing it. For the purpose to answer our question I will be taking IonMonkey, the JS engine built by Mozilla in context.</p><h4>JS Invoke Steps</h4><p>So the steps in which a single Functional Block is been executed by JavaScript follows the following steps.</p><ol><li>Load the Code in memory</li><li>Generate an intermediate binary code(JS OpCode generation)</li><li>Interpret that code</li><li>Bailout, and initialise environment variables, context, stack and other necessary things required to execute that block.</li><li>Execute the block, save the return states onto the stack, call the callee and jump out of Bailout.</li></ol><p>Now, the answer we are looking for our question exists in the 2nd step i.e. Javascript OpCode generation.</p><p>Javascript might be the most versatile language but it too has set limits for few things, like <em>setTimeout 0(zero)</em> is never exactly <em>0ms</em>, its a predefined constant value, some JS engines has set its value to 5ms and other have variant implementation of the same, similarly there is one major limit on calling a function that is, number of arguments!(It’s your homework to figure out what’s the exact count). You can’t pass any number of arguments to invoke a function, you might have got a hint here a little bit about the answer but read on there is little more for your surprise.</p><p>A typical JS block/Script/Function is executed until the opcode <strong>JSOP_RETRVAL</strong>, <strong>JSOP_RETURN</strong> is encountered. So what are OpCodes?</p><h4>OpCodes</h4><p>An OpCode is basically generated by JIT(Just-In-Time) compiler of JS Engine, these are symbols which converts the given code into an engine understandable format, an example of a JIT is CrankShaft that v8 uses. So yeah, the code is compiled first, and then interpreted, but don’t worry a JS compiler never throws any error for your script except Syntax Errors. These compilers perform the primary level of optimisation for your code, it converts your code into tokens which have specific meanings for the Interpreter to understand, an example of optimisation are Atomic values e.g. accessing the length of an Array or an Object i.e. <strong>JSOP_LENGTH</strong>, it is by default optimised for faster execution. So our dear apply() and call() have their opcodes too i.e. <strong>JSOP_FUNAPPLY </strong>and <strong>JSOP_FUNCALL </strong>both are parts of <strong>JS_INVOKE </strong>opcode. A <strong>JS_INVOKE</strong> opcode means that this statement need to be invoked separately out of the current running context.</p><p>Now what happens with call() is pretty basic, do you remember the C language’s variable length argument declaration? Something that looked like this.</p><blockquote><strong><em>int</em></strong><em> </em>someCoolFunction<em>(</em><strong><em>…</em></strong><em>)</em></blockquote><p>Yeah, I know you might be laughing now, because we cracked it, almost!</p><h4>The Catch</h4><p>Whenever you invoke the call() function of Function.prototype, where Function could be any JS function(anonymous, named) that call to function by default gets converted to <strong>(…) </strong>a pretty basic optimised implementation. The interpreter now don’t have to worry to expand the arguments when calling that function instead what it does is just point it to the list of arguments that you provided to someFunction.call(), which are easily available on the stack itself.</p><p>A Bailout of call when triggered, picks the first argument as the pointer to the *jscontext for the next bailout(actual execution of the function which is been called) and all other arguments following it which are already available on the stack are directly passed to the function for which the call() is invoked.</p><p>Now the only drawback with call() is the number of arguments, whenever you invoke call(), you are passing a predefined length of arguments. You can’t pass arbitrary number of arguments using call and as I said its your homework to figure out that limit. So, when Douglas Crockford and team were developing JS they thought of this use case when the programmer can have an arbitrary length of arguments which they might not know about when they want to invoke a function, so they found a workaround for it, and that is the apply() function. An apply function takes the second parameter as an array of arguments. Now when the Bailout is triggered by the invocation of apply() function, JS Engine picks the second parameter, expand it and apply those to whichever function you have triggered apply on. This task has its own cost which is, traversing the array, picking each element, pushing onto the next calling stack of Bailout one by one and then invoking it.</p><p>An apply() function too has the same limit on length of arguments, so don’t think that you can pass the whole list of unique ID’s of Penguins that lives on Antarctica(C’mon atleast for next 5–10 years until we make them reach near to extinction)(:angryface:).</p><p><em>Function</em>.<strong>prototype</strong>.<strong><em>call</em></strong>() and <em>Function</em>.<strong>prototype</strong>.<strong><em>apply</em></strong>() both will give you a <strong>Stack Range Limit</strong> Error if you try to pass a very long number of arguments to a function.</p><h4>Conclusion</h4><p>Javascript is the most awesome thing that could happen to the programming world, a freedom to code, a speed of execution and lot more things. The frameworks that are built upon JS have their own individual drawbacks and are often correlated with that of JS(:<em>shrug</em>:) which I think is quite baseless. There is lot about JS, internal specs, performance metrics, that I will keep on exploring and sharing with you all, every week, I would rather expand my studies to other languages too provided they have an Open Source Code available on Git(C’mon give me some break!). You can comment and let me know about this post and what you will love to read about in my next upcoming posts.</p><p>With ❤ ! Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6650a4352206" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>