How do Javascript files continuously run?

I'm having a big conceptual problem trying to make a primitive paint app. This is my first "big" project, and I'm hoping to learn how to make interactive webpages with this project. I've learnt how to make static webpages and some interactive elements in html and javascript (e.g <button href="webpage.html">) and understand how that works - the interpreter runs through the code from the top and just does what it reads. And then thats it.

Problem is, how does the js file work? If below </body> I put <script src="main.js>, isn't this file just run .... once? and then the intepreter goes to the end of the HTML file and thats it? Maybe its because the JS file just acts to change the DOM and then it goes from there? No idea really.

My background is in leetcode and scientific programming, wherein I made programs that just ran and then returned a result, so this is my first time making continously running programms.

Thanks very much.

30 comments · 83% upvoted · other discussions

comments

[deleted]

Javascript is triggered by events. For a paint program, you are going to be using mouse events.

https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove\_event

Ryuuji159

Yes, javascript just executes once, but in that execution you can create events for user interaction, browser events, etc. in the browser javascript is an event driven programming language.

sillyd0rk

This should give a much better understanding

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

mr_axe

Yeah, the event loop is the big thing here

KinksAreForKeds

When you write a <script> tag, that is just the point in the HTML at which your JavaScript is loaded into the interpreter. If there is JS code that needs to run right away, then it's executed... but in general you're just telling the interpreter what events (like mouse clicks, window resizes, time passing, etc) to tie the bits of code to. So nothing is really executing, it's just sitting there waiting for those specific events to occur. And if so coded, any time a specified event occurs, the appropriate code is run.

shgysk8zer0

I suspect that a paint app is probably beyond what you should be working on at this point. If you don't understand events and think that interactivity is <button href="..."> or that scripts come at the closing </body> tag... You're getting in way over your head.

  • event listeners are basically how JS runs continuously (that and polling and similar techniques)
  • href isn't interactivity, it's just basic (and static) "hypertext"
  • href doesn't work on <button>... You're probably thinking of <a>
  • <script> often are included before closing <body>, but that's mostly to support ancient IE that isn't used anymore .. we use <script defer> in the <head> now

You should really get used to event handlers through some common usage of "click" handlers long before even thinking about creating a paint app. Paint apps are fairly advanced in terms of handling multiple more complex events and probably <canvas>. You properly want to learn to crawl before entering a marathon.

13thtryatausername

I see where you’re coming from, but in my experience, diving into the deep end on something you really want to make is the quickest way to learn.

I think the better advice is to encourage learning about all the things you mentioned WHILE building the painting app.

There’s nothing more discouraging than trying to learn a new language/framework/concept while building something meaningless to you. It doesn’t work, at least not for me.

RagingWalrus1394

This x1000. You have to care about what you’re making and want to invest time into it. For every project I’ve ever done, if I’m not invested in it then my eyes just glaze over trying to comprehend documentation and I end up frustrated because I don’t know what I’m looking for or how to word a google search.

I think the only thing I would add to this is to always do your projects twice. The first time through, just start coding. Get everything to work, figure out how you want to build it. The second time through you’ll have a much better understanding of what’s needed and you can really optimize everything and make it a clean running program.

[deleted]

[deleted]

shgysk8zer0

It shouldn't be. Nobody starts off running... We all have to crawl first.

[deleted]

There are some good talks on the event loop which might help with overall understanding

GraphiteEaterArt

I do a setInterval(() => mainScript(), 1000); EASY

HuWeiliu

This is a weird response, thus the down votes, but setInterval can be used like this in some contexts - such as building a canvas game, where you want to be continuously rerunning the rendering system. Obviously in that case it would be more frequent than 1 second

Mclean_Tom_

familiar workable work yoke bells enter resolute tidy whole market

This post was mass deleted and anonymized with Redact

Shigalyov

I've just started learning jQuery (like literally today). I learned JS itself by myself for a few years so I know I'm missing obvious things other people know.

But I see with jQuery it makes sense to put coding in <head> with "ready"? With JS itself I thought we put it near the end of the body tag. This is off topic to the OP, but seems some of the comments are talking about it.

As to the OP, conceptually I understand it that the browser recognizes events like clicking and hovering. When that happens, it looks through the .js files for event-related code? I have no idea, but that's how I make sense of it.

Mentalpopcorn

For a paint program you'll likely want to look into the state pattern. If you're able to implement it I think you'll have answered your question by the end of it.

https://en.m.wikipedia.org/wiki/State_pattern

The Gang of Four's Design Patterns also discusses using the state pattern for a paint program specifically. You should be able to find a PDF if you don't own it (but every dev should tbh)

thaibobatea

As someone who is a comp sci programmer that does web design, if your background is in strongly typed languages, I would recommend using TypeScript instead of JavaScript. TypeScript is a wrapper for JavaScript which makes it strongly typed.

https://www.typescriptlang.org/

mahamoti

I want some of whatever you’re putting in that boba tea if you think OP is ready for typescript based on this post.

spinning_the_future

I'm convinced that typescript is a cult.

thaibobatea

OP mentioned they do scientific programming so I gave a different option that could make the transition easier

mahamoti

There's a place for typescript. Newbie projects when they're still learning static HTML and event JS isn't it. OP doesn't know which tag the href attribute goes on, but you want them to transpile ts?

Zephrok [OP]

Thanks man I'll look into it when I'm a little more comfortable with JS.

eablokker

It depends what you write in your javascript file.

If you just set some variables, write and execute a function, do some math, and print out the result to the console, then yes that is run only once. However after it is done, the variables and functions are still in memory, and you could potentially use them again at a later time. Once the javascript is done running, it doesn't quit, it stays there forever in the browser until you close the tab.

But the usefulness of javascript is to make the web page interactive, not just run once. This is accomplished with event listeners. For example, you can listen for when the mouse is clicked on a button. Once you create a listener, it stays there in memory forever until you close the tab or destroy the listener. The code you write inside the listener's function will get executed every time that particular event happens, like when the mouse is clicked on a button. So you could write something that says when this button is clicked, execute this function that I wrote earlier, with this variable I set earlier, and print the result to the console. The browser is always watching for that button click event to happen, forever, and is ready to execute your code when it does.

If you were writing an interactive game, then you would probably write an infinite loop which on each iteration of the loop it does something in the game or moves characters on the screen. This type of program runs forever until you break out of the loop.

AaronDNewman

The javascript is run in the context of the browser. The browser always executes the code in the 'script' tag after the html and all the static links are loaded. Usually the code will listen for events that the browser provides (like mouse clicks), or sets timers to do things at different intervals, since those are useful things for a browser program to do. But if you write a program that just executes to completion and prints a result, it would be pretty similar to how leetcode works.

Outrageous-Chip-3961

yes it runs once each time you download it. You can call functions within that file after it has run however, by using events such as mouse listeners and click handlers.

You may benefit from learning how to make a little javascript 2d game. The 'game loop' does a pretty good job conceptually to help with this, at least it helped me.

Skizm

JS registers events with the browser. The browser is the one actually responding to user events.

vincent-vega10

Yes, JS indeed runs only one time. BUT, JS uses certain APIs to make sure you're interacting with your web-app. And these APIs are not inherently present in JS, but are provided by the browser you're running your files on. Some of them are addEventListener, querySelectorAll, setInterVal etc., The DOM itself is provided by the browser.

While the JS file is loading, when it comes across such lines of code utilizing a browser API, it informs the browser, and all the things that happen in the future are done by the browser.

For example :-

document.getElementById("btn-a").addEventListener("click", function() {
    console.log("Button clicked")
})

When this above code is ran, JS informs browser to keep track of click event on the button you've specified and run some code when the click action is performed. In the future, whenever that button is clicked, the browser will run the code inside the function.

This comment explains how things happen in an abstract manner. For overall understanding on how things work behind the scenes, you can look into what event loops are. (It is also one of the most-asked questions in interviews)

Ireeb

Events and Event Handlers.

The simplified version is: In the file, you write "if this happens, do that". The interpreter reads that once, but basically "remembers" and will execute the commands when the Events you specified happen.

The simplest event is probably the "click" event. With it, you can tell the script to execute a function when a specific element is clicked.

Commercial_Wing_7007

If you need <script> to trigger the code to run before it reaches the end of HTML, you will need to add your Javascript tag in the head to read before the HTML. It's all read in order, usually having the Javascript be the last touches when everything loads if <script> is below the document. This is customary.

You will also need to run your functions accordingly. Can DM you a few pages of the textbook I have about it if you want more detail. It's Javascript and jquery by Jon Duckett, good textbook.

lenswipe

They don't. As others have said they listen for and respond to events.