What's the benefit of trying to minify or shorten the code in situ? As Sean showed, you can always plop it into a minifier, but while coding, shorthand like
let p=x => document.querySelector(x);
is probably not too helpful to your future self that might want to maintain or debug the script. Sometimes I see this aliased using the $
variable (when jQuery isn't otherwise being used:
const $ = x => document.querySelector(x);
const $$ = x => document.querySelectorAll(x);
(note I've used const
instead of the weaker let
; we don't want to accidentally reassign this variable)
Style nitpicks
I'd suggest using an autoformatter like prettier or the internal Stack Snippets editor.
function delay(n){
-> function delay(ms) {
setTimeout(resolve,n);
-> setTimeout(resolve, ms);
while(true){
-> while (true) {
or for (;;) {
1000
is much clearer than 1e3
to me -- it's not worth shaving a character.
Bigger issues
The line:
if(x=p(".dialog-box")) {
creates a global variable x
attached to the window which can potentially cause a bug. If you put "use strict";
at the top of your script, you'll get a nice error protecting you from yourself. As a rule of thumb, don't do assignments in conditions like this unless you really know what you're doing and are sure it's going to read more cleanly than moving it to a separate line.
If you're running this as a bookmarklet or userscript on another site, I would put all of the code into the IIFE closure so to avoid clashing with globals.
Secondly, do you need to poll like this, or can you use a MutationObserver
? Observing mutations means you won't need to burn cycles continually to keep checking the predicate; the code will only run when there's a DOM mutation on the watched subtree. Without seeing a representative sample of the page this works on, it's hard to say much more though.
It's probably not applicable here, but requestAnimationFrame
will give you a tighter polling loop and is often a useful tool for these userscript situations.
A quick rewrite
(async () => {
"use strict";
const delay = ms => new Promise(res => setTimeout(res, ms));
const $ = x => document.querySelector(x);
for (;;) {
await delay(100);
const elem = $(".dialog-box");
if (elem) {
elem.style.visibility = "hidden";
await delay(1000 + 4000 * Math.random());
console.log(new Date().toLocaleTimeString() + ": Clicked");
$(".here-button").click();
}
}
})();
<div class="dialog-box"></div>
<button class="here-button"></button>