Signposts in Code

When we write code, we often find ourselves pressured to work faster, sacrificing the quality of the product.

Something We can do as Developers:

Clockmakers leave subtle marks to help guide the next person who has to work on that clock - we developers should do the same, it makes everything better for the next person to work on the code, even when that person is you!

Software Engineering is the field I know best about, and this will probably make little sense to people who are not in it.  Specifically FE people in particular might appreciate this post most, as TS is my language de jour.

Double Bang:

Using `!!` at the front of a line, such as:

`const foo = ((thisThis || thatThing ) && (theOther thing && thatOtheThing))`

If you instead write:

`const foo = !!((thisThis || thatThing ) && (theOther thing && thatOtheThing))`

I IMMEDIATELY know that this is going to be a `boolean` with the value of whatever this check returns.  Without it, I need to read the entire thing, then I see there is nothing else, say turnary, it’s just straight this.

Ternaries:

Don’t use double (or more) turnaries!!  They suck, they are hard to mentally process,  and waaaaay too many times I have found bugs specifically because they are bad.

Single ones are totally fine.  Double or higher, you need to break it up.

Single ones are fine.  Double or higher, you need to break it up. 

Again, it sacrifices having code in-line, and instead makes you move things to a function…That I hope you named after what it does! Something something something 2 hardest problems…

IF and Other Statements:

Well, there is too much here to talk about, so I will address the first ones in my mind.

Curly brackets – always use them, unless you can put everything on one line:

“`

if(foo) return bar;

FINE

if (foo) {

Do something!

}

FINE

If (foo)

Do something

BADDDD!  – people will add stuff and not realize there are no curly braces, so their thing after won’t actually fire.  Putting everything on one line is a Signpost that tells us “there are no braces, this is a stand-alone statement.

Functions:

These can be written several ways!

  1. `const foo = function(x) {return ‘But Why!?}`
  2. `function thingyImDoing(…)`
  3. `const bar = () => {return ‘But Why?’}`

Obviously there are more, but these are the basics.

These all do different things.  There are more, but these are the ones most use, and therefore are the ones we should cover.

Do you know the difference?

#2 Is what is known as a “function expression” – these are special.

When you use #2 for function is always there (see: function scoping)

I use this option specifically when I have a lot of code, I take advantage of “hoisting” and put these at the bottom, because I am satisfied with name “removePersonFromEmail()” to be a Signpost that tells me what is happening here.  It also preservers the this binding – not super important these days, but you should be aware especially if you are using jQuery or similar libraries.

#3 is Arrow Function (IE: “Fat Arrow”) – all the cool kids write them this way these days.  You should think about it first though, can you introduce a Signpost?  Mostly NOT using them IS the signpost.  If I see the `function` keyword I know I need to be aware that there is code at the bottom of the file that I need to look at for a more holistic view.

#1 Signpost that tells me you suck…why are you even doing this?  Can it actually make sense?Generally not. …It is _I think_ an unnamed function expression – actually, I kind of want to know what happens – it is unnamed, so the definition might be hoisted in an unusable way? But since it is a const, it would hit the Temporal Dead Zone…Ok, the reason you would use it is because you want to preserve the this binding but don’t need hoisting? That’s my best guess on what would happen. THAT SIGNPOST SUCKS!

Const and let:

These are obviously Signposts – they tell you if a var will change or not.  If it is a `const` it will always be that value – if it is `let` it could be something totally different….Except blah blah blah.

The above are just a few examples of Signposts we can use.  You should come up with more of your own!  If you have any that you LIKE, PLEASE COMMENT BELOW! Also, as always please tell me where I am wrong – I do not like being wrong – It makes me even more upset if I give other people incorrect information.

Is React’s setState Asynchronous?

For this post I am talking about in React when you use (see: https://react.dev/reference/react/useState):

const [foo, setFoo] = useState(“bar”);

And then you use:

setFoo(“fizz”)  ← This right here

Let me ask you a question:

Is setState Asynchronous?

  1. Yes!
  2. No!

Trick question, the answer is “Well, it’s really complicated, and you should just assume it is.”

However…If you want more information about it, I can give you an answer in several parts…It’s complicated.

I feel like the true answer depends on the exact definition of “asynchronous.” So let’s explore how `setState` actually works.

Going deeper:

setState executes in two parts, the first part executing immediately, the second part executing later, however that second part is immediately added to the event loop…Actually that second part isn’t totally true.  It’s not technically added to the event loop – it tells React that it needs to re-render, the check for that is already on the event loop in React’s internal event loop…So technically, it’s not added to the end of the event loop, basically a flag is set saying “do a re-render” and that re-render happens after the current render finishes, when React gets to that check in its internal event loop.

We need to be clear about two different parts of state in React for this to make sense.  

  1. React maintains an internal state that is (usually – it is exposed in updater functions…for brevity, I’m stoping here) not exposed to you, the developer.  
  2. There is also a component state in the example above, this is  foo.

These two states are sometimes the same, and they are sometimes different.

The first thing it does is execute an update to React’s internal state (#1 above).  That is totally immediate, and I don’t think anyone would argue that it is asynchronous.  

When React’s internal state is updated, React tells itself  “I need to do a re-render.”  This re-render however is deferred till after the current render cycle is completed.

This means that the state inside your component (in the example at the top foo, #2 above) is NOT updated till that re-render.  The state inside your component only ever changes during render.  This is true for anything involving state in your component.  More simply: component state only ever changes during the render cycle.

So, is that second part asynchronous?

Well, you can’t await is, so no, it’s not, end of story…Except you can’t await setTimeout and I think we generally agree that setTimeout is asynchronous…You can however wrap setTimeout in a Promise and you can await that…Turns out, you can also wrap a setState in a promise and await that…But don’t ever do that because it makes React unhappy and throw errors.

Fact: React will always execute setStates in the same order, so the last one will always be the final value.  

Fact: You need to use an updater function if you want to access the current internal React value (#1 above) – meaning, if the current render has updated the state, the only way to see that updated state is in an updater function. 

Fact: You CANNOT access the current internal React value of a DIFFERENT state value (during the current render cycle) in your component, even in an updater function.  Meaning, if you have two state values, and you update one, then you update the second one – with or without an updater function – you will ALWAYS get the un-updated value of the first one.  Why: Because component state (#2 above) only changes on the re-render, and that doesn’t happen till after the current render completes.

By “asynchronous” do we mean “doesn’t execute immediately?”  Do we mean “Is added to the microtask queue?” …Does setTimeout(..., 0) count as asynchronous? A lot of what I read says “does not hold up execution” which well, it doesn’t, except it does after other stuff…

Well, that lead me to reading the ECMAScript spec about setTimeout and I couldn’t discern if setTimeout(..., 0) is added to the event loop, added to the microtask queue, one of the previous but with a slight delay, or something else…I’m actually not sure that the behavior is defined – If someone smarter than me knows the answer to this please let me know.

What I do know is that a setTimeout(...,0) will always execute after the re-render cycle (I know this because it obviously isn’t part of React’s render cycle and always is the final update – in my testing) – meaning, that if you have a setTimeout(...,0) that sets the state, as well as other settings of the same state, the final value will always be the one set inside of the setTimeout(...,0) …Except that I say “always” and I actually don’t actually know if that is true.  It is true in my testing.  If that setTimeout is added to the microtask queue, in between other tasks that set that state, then it is possible that it won’t be the final value…but I don’t know if it is…but generally it is true – at least in my testing…And again, I’m not totally positive that is even defined in the spec…and we are splitting hairs here.

Because I don’t think that is complicated enough, React was kind enough to make running in dev mode as opposed to prod work differently.  Well, kind of.  If you are using an updater function, React will update twice in dev mode, and once in prod.  Why?  Oh god how deep does this hole go? 

Short answer: it should be a pure function. (see: https://en.wikipedia.org/wiki/Pure_function & https://react.dev/learn/keeping-components-pure)

Technically when React tells itself it needs to re-render, it applies the update to that component state var (#2) to it’s queue with the current internal value (#1) of the variable – meaning that changes to that variable inside of an updater function ARE NOT SEEN – as the original value was already applied, when the call was queued.  So if you update the state of the variable inside of an updater function, and then try to update it again later with an updater function, the first update is ignored.  Meaning: that’s a really bad idea.  So, in dev mode React will run it twice, once with the first value, once with the second value, and if they are different, ya done goofed.  The reason it does this in dev mode is to show you that you goofed.

So again, how is “asynchronous” technically defined?  And is it asynchronous?  IDFK.

I say setState is not asynchronous because the execution order is defined, and everything it does is immediately added to the the event loop when it is called – if you know what you are doing, the results are deterministic, you absolutely know what the final result will be.  I say please don’t ever rely on this, because the next person who has to modify the code – including future you – is generally not smart enough to understand the nuances here, and if your code relies on this behavior, they will likely break things.

I also say it is asynchronous because part of it executes out of order, and we can (in theory) use a promise to `await` it.

Additionally – because this behavior is so esoteric, I don’t know that it will not be changed in React, sometime the future.

ALL OF THIS IS WHY I SAY TO JUST TREAT IT AS ASYNCHRONOUS! 

I probably made some technical mistakes above…Though I do think it is basically correct.  What I wrote is based on my reading many things, watching many things, and a butt load of tests I wrote myself….Really, I should have saved those tests so I could post them…If you want me to reproduce and post those test, let me know.

PLEASE LET ME KNOW IF ANYTHING I WROTE ABOVE IS INACCURATE.

Bookmarklet For Increasing YouTube Speed

I made a new tiny bookmarklet to let you increase the speed of a YouTube video beyond 2x.

As always, just drag this link to the bookmark bar on your browser, then just start a YouTube video, once the video starts, click the bookmark, and enter how many “x” you want the video played at. I usually stick to 2.5 or possibly 3, it all depends on the video – but you do you!

YouTube Speed

The code is pretty simple and easily found online, but just in case that’s what you are looking for:

(function(){document.getElementsByTagName('video')[0].playbackRate = window.prompt('Please enter a new speed:');})();

Facebag – A Chrome Extension to make Facebook less interactive!

Long time no update! Well, I just made myself a little Chrome Extension for Facebook. All it does is delete the comment boxes, status box and like buttons from Facebook, so that I don’t use them. It’s great for me! I am considering adding other things to it as well, but for now this was quick and dirty and did what I wanted!

Chrome Store Link

Github Repo

Netflix Autoplay Chrome Extension – v0.8 – Chromecast Support!

I put out an update the other night, this one adds support for Chromecast.

And it looks like I was just in time for the new season of Orange Is the New Black, so get your binge on!

Web Store: https://chrome.google.com/webstore/detail/netflix-autoplayer-with-s/adegickccmlojbmbmemgjakpoammfmkg?utm_source=chrome-ntp-icon

Github: https://github.com/rtpmatt/Netflix-Autoplay-Chrome-Extension

Netflix Autoplay Chrome Extension – Still More Updates

I have added still more updated to my Chrome extension.

0.6 Updates:
*Added episode counter in addition to timer
*Pausing video stops timer
*Fixed bugs when stopping

0.5 Updates:
*Play/Pause, Next and Stop media buttons on keyboard now work with Netflix.
*ctrl+q now causes the same action as the sleep timer ending (ex: pause movie & sleep).

Chrome store link: https://chrome.google.com/webstore/detail/netflix-autoplayer-with-s/adegickccmlojbmbmemgjakpoammfmkg?utm_source=chrome-ntp-icon

Github link: https://github.com/rtpmatt/Netflix-Autoplay-Chrome-Extension

Netflix Autoplay Chrome Extension with Computer Sleep / Shutdown – Updates

I have added a number of updates to my Netflix autoplay extension. In addition to autoplaying TV episodes and shutting down when done, it now also adds support for the keyboard media keys play/pause, next, and stop to Netflix, and also adds a new keyboard shortcut of ctrl+q which does the same thing that will happen when the timer reaches zero. The extension and Github have both been updated.

Also, a little while ago I added default value options for the popup that can be set in the extension option.

Github: https://github.com/rtpmatt/Netflix-Autoplay-Chrome-Extension

Chrome Store Link: https://chrome.google.com/webstore/detail/netflix-autoplayer-with-s/adegickccmlojbmbmemgjakpoammfmkg?utm_source=chrome-ntp-icon

Netflix Autoplay Chrome Extension – With System Sleep!

Bookmarklets are cool and all that, but what I have really always wanted the autoplay functionality for Netflix to do is emulate the ‘Sleep Timer’ found on most TVs. That is, I want it to play for some amount of them, and when done, shut everything off. I know I am not the only person around who has used the function on the TV for years while going to sleep. I have known that this is not possible using just a bookmarklet, but I never got the energy up to actually figure out how to make one. One of the reasons is that I have always known that calling something external like the Shutdown/Sleep command on the computer would be a huge pain. This new HTML5 video Netflix is using for Chrome though made it just a bit too tempting.

The core functionality works basically the same way as this one, since Chrome extensions just use Javascript. I had to figure out how to do all the fancy stuff that makes it an extension, AND add the stuff to allow it to interact with the system to call the Sleep command.

And here it is: Netflix Autoplayer – Chrome Extension

IMPORTANT:
For the ‘Sleep’ functionality to work, once you have installed the extension, you must download the install.bat file that you will see a link for at the bottom of the dialog for the extension. You must run this (and I believe you might need administrator privileges when you do) it creates a couple files that are needed and adds a registry entry. Really, in general I would say you should not do something like that. You shouldn’t be running random things people on the internet tell you to. If you want the ‘Sleep’ to work though, that’s what you need to do. If you understand how .bat files work, it is actually really small, so you can check out what it is doing.

Once you have done the above you can actually edit one of the files it creates, it is located at:
%LOCALAPPDATA%\Netflix-Autoplay\shutdown.bat

And by default should have the following:

:: Lock
::rundll32.exe User32.dll,LockWorkStation
:: Shutdown
::Shutdown.exe -s -t 00
:: Hibernate
::rundll32.exe PowrProf.dll,SetSuspendState
:: Sleep
rundll32.exe powrprof.dll,SetSuspendState 0,1,0

As you can see, ‘Sleep’ is what it does by default, but I have entries for Hibernate, Shutdown, and Lock all listed, just uncomment the one you want and comment the others back out…Hell if you want you could really put anything you like in that file and make it run anything when the timer gets to zero.

Chrome Web Store Link: https://chrome.google.com/webstore/detail/netflix-autoplayer/adegickccmlojbmbmemgjakpoammfmkg?utm_source=chrome-ntp-icon

Github Link: https://github.com/rtpmatt/Netflix-Autoplay-Chrome-Extension

Hope you enjoy!

NEW Netflix Autoplay Bookmarklet!

GOOD NEWS EVERYONE!

I was checking out Netflix today, and they seem to have moved to an HTML5 video player (for me in Chrome at least, and that is all I tested). This is awesome news as it made writing a new autoplay bookmarklet easy as shit! They also got rid if the bit of Javascript they were trying to use to prevent you from using the console. I don’t know why they made the decision to get rid of that, it could be because they know it is a dumb idea and anybody who actually knows what they are doing can get around it, it could be because they are now OK with people playing around, it could be just an accident, but I am going to take personal credit for it because of this post: I Don’t Like Being Told What I Can and Can’t Do.

Anyway, as I said, this awesome new HTML5 video player made my job super easy – as you can see by how much less code there is this time…and here it is:



‘use strict’;
(function(undefined){
//Check if user has already loaded an instance – if so, just update the play time;
if(window._ME && window._ME.autoplayer) {
//Get desired play time extension & convert to miliseconds
window._ME.autoplayer.playTime = window.prompt(‘Autoplay already started! Updating playtime. \n How many more minutes would you like to play for?’) * 60 * 1000;
if(isNaN(window._ME.autoplayer.playTime)) {
window.alert(‘That\’s not a number jackass.’);
}
window._ME.autoplayer.startTime = new Date();
return;
}

window._ME = {
autoplayer: {}
};

//Get desired play time & convert to miliseconds
window._ME.autoplayer.playTime = window.prompt(‘How many minutes would you like to play for?’) * 60 * 1000;
if(isNaN(window._ME.autoplayer.playTime)) {
window.alert(‘That\’s not a number jackass.’);
}
window._ME.autoplayer.startTime = new Date();
var lastUpdate = new Date();

//Checks if the video has stopped or if we are done playing once a second
window._ME.autoplayer.interval = setInterval(function() {
var currentTime = new Date();

// Check if autoplay-interrupt has fired
if(document.getElementsByClassName(‘player-autoplay-interrupter’).length > 0 && document.getElementsByClassName(‘continue-playing’).length > 0) {
//Just click the continue button!
document.getElementsByClassName(‘continue-playing’)[0].click();
}

//Check if at end of season
if (document.getElementsByClassName(‘player-postplay-autoplay-header’) && document.getElementsByTagName(‘video’).length === 0 && document.getElementsByClassName(‘player-postplay-still-hover’).length > 0) {
//Click the next video picture
document.getElementsByClassName(‘player-postplay-still-hover’)[0].click();
}

//Check if we have reached the users max play time
if(window._ME.autoplayer.playTime && currentTime – window._ME.autoplayer.startTime > window._ME.autoplayer.playTime && document.getElementsByClassName(‘player-play-pause’).length > 0) {
//click the pause button
document.getElementsByClassName(‘player-play-pause’)[0].click();

//remove all traces of this autoplayer
clearInterval(window._ME.autoplayer.interval);
delete(window._ME);
}

lastUpdate = currentTime;
}, 1000);
})();
[/sourcecode]

Basically all I had to do this time was watch for when the right elements popup on the screen, and when they do, click them. Thank you Netflix!

The Thing You Want:
[raw]
Here is the Bookmarklet: Restart Timer
[/raw]

Turn off Autoplay:
[sourcecode language=’javascript’]
(function() {
clearInterval(window._ME.autoplayer.interval);
delete(window._ME);
})();

[raw]
Bookmarklet: Turn off Autoplay
[/raw]

If you are new to this, to use these, simply drag those links up to your bookmark bar, then start up the TV show you want to watch, and click the first bookmark.

The bookmarklet will ask you how long you want to play for, and it will pause the video and remove itself when it hits that time limit. For never-ending play, just enter “0”.
-If you hit it a second time, it will as you again how long you want to play for, and restart the timer with the new length.

If you hit the second bookmarklet I have there, it will restart the timer. Meaning that if you put in “60” (for 1 hour of play time) hitting it will restart the countdown back to 60 minutes.

If you hit the third bookmarklet, it will remove all traces of the bookmarklet from the page (basically the same as just hitting refresh on the page).

This should have no problem with multiple seasons, or any of that fancy stuff. Let me know if you find any bugs, I may do something about them I guess.

And I should have this up on GitHub shortly here: https://github.com/rtpmatt/Netflix-HTML5-Autoplay-Bookmarklet

Update:
Yeah, I just tried this in FireFox, and apparently it still uses SilverLight, not HTML5 videos, so this wont work at all in it. So, please don’t tell me about how it is broken in FireFox, I will not be doing anything about that…If you are using IE, then I REALLLY don’t care if it works or not. If you send me anything about your IE situation I may send you back an insult, or possibly a picture of a cat butt, that might be fun for you I guess? I don’t know if you will be able to view them on IE though.