Home > Software design >  Javascript not functioning properly on my whole system
Javascript not functioning properly on my whole system

Time:01-29

SOLVED: So the problem was that the program broke at when I declared userInput but that was already declared in the js file that I initialized right before this app.js file. Once I changed the name it seems to be better now, thanks all! :D

So i've started a JS tutorial and all the code is doing weird things and not executing in the proper order no matter how many times I close and reopen the program.

I am working on a calculator program from the tutorial so i've copied the code how it appears.

Here is the file structure:

enter image description here

Here is my index.html (notice the script tags at the end of the body)

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Basics</title>
    <link
      href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="assets/styles/app.css" />
    
  </head>
  <body>
    <header>
      <h1>The Unconventional Calculators</h1>
    </header>

    <section id="calculator">
      <input type="number" id="input-number" />
      <div id="calc-actions">
        <button type="button" id="btn-add"> </button>
        <button type="button" id="btn-subtract">-</button>
        <button type="button" id="btn-multiply">*</button>
        <button type="button" id="btn-divide">/</button>
      </div>
    </section>
    <section id="results">
      <h2 id="current-calculation">0</h2>
      <h2>Result: <span id="current-result">0</span></h2>
    </section>
    
    <script src="assets/scripts/vendor.js"></script>
    <script src="assets/scripts/app.js"></script>
  </body>
</html>

I put the script tags at the end of the body so the site content is generated first but it still runs the script first sometimes, and only when I refresh enough times does it stop. Weird...

app.js

let currentResult = 10;

currentResult = currentResult   10 * 3;
let calculationDescription = `${currentResult} (0   10)`

outputResult(currentResult, calculationDescription)
alert("hello")

enter image description here

And then when I press Ok on the alert

enter image description here

Only then does the calculation get done. Which is strange because the calculation is written to be executed BEFORE the alert (The calculation did appear a few times while the alert was active, but only 15 seconds later, it doesn't even do that anymore)

When I add..

const userInput = 123;
let result;

After the alert in app.js, the alert stops running entirely! This makes no sense to me. I wanted to have some js code after the alert so I can put in another alert but this file is making it seem like the alert MUST be the last thing in a js file OR there can only be approx 5 lines in a js file.

Also, the css in the project wasn't working until I moved the entire project from my downloads folder to my desktop (and removed the 5 parent folder hierarchy over it) and there the css did work...

Any idea what can be causing this mess, or is my computer just cursed?

Assumptions:

  • I've saved the code so it is fully updated
  • I am using VScode
  • Running from my OneDrive folder on Windows 10

CodePudding user response:

You essentially asked three questions here:

  1. Why do I see result of my calculation only after closing the alert?
  2. Why does adding const userInput = 123; let result; after the alert prevent the alert from showing up at all?
  3. Why is my CSS not working in some circumstances?

Let me answer all:

Answer to Question 1: Order of execution

The code does execute in order. You can see that if you use the devtools debugger to step through it line by line. What's tripping you up is when the browser redraws page content, as this happens at the end of a tick, when there is no more code to be run in that tick. Rerendering the page instantly whenever something on it gets changed would be very slow (and could induce flicker, depending on what it is that you are updating).

So what happens is this:

  1. Your calculation result is set as content of your element. (But you don't see it yet since the page hasn't been redrawn yet.)
  2. Your alert shows up.
  3. You close the alert.
  4. The call to the alert function returns and the code continues.
  5. No more code is there to run (at least synchronously), and the page is redrawn. (Now you see the changed content.)

In the rare cases where the calculation did show up 15 seconds later, it was probably that something else, something external (such as maybe resizing the window) triggered a redraw despite the alert still being open.

alert isn't the best way to get output anyway, for several reasons: it also obscures a lot of information about more complex data types because it coerces everything to a string, and you cannot easily trace the source of the alert or log the exact time it was shown - all of which are things that console.log would do better.

Answer to Question 2: Why adding code can break everything

Most likely you were introducing a syntax error at that point. For example you may have already declared userInput or result previously, and adding that code made the whole file invalid with a SyntaxError: Identifier 'result' has already been declared or the like, so it wouldn't execute at all.

That's because when a script file (or a <script> tag content) is loaded, it's first parsed (at which point you can encounter "compile-time errors" such as a SyntaxError) and only then it's executed (and then you can encounter "runtime errors" such as a ReferenceError). If you add a single bad character at the very end of your file that's causing a SyntaxError during parsing, the whole file will no longer run.

You would see this error and where it originates from if you'd look into the console tab of your devtools.

In general, I can only recommend learning how to use devtools rather sooner than later: https://www.youtube.com/watch?v=Y3u2groOG-A

Answer to Question 3: Missing styles

It's hard to tell with the information given. Again, a good start would be to check in your devtools for errors in regards to loading the CSS file (in console and network tabs). Also, in case you are using a file:// URI, I'd recommend switching to a local HTTP server instead. Many things behave differently with file:// URIs compared to http:///https://.

CodePudding user response:

You'll likely want some sort of event listener to ensure that the alert is only triggered after a certain action. With the way the code is currently written, as soon as the page loads it's going to execute your entire JS file, thus triggering the alert.

  •  Tags:  
  • Related